在Python中使用shell命令的幾種方式總結

在Python中使用shell命令的幾種方式總結

有時會有在python中使用shell命令的需求,在此整理了三種在Python中使用shell命令的需求並提供部分代碼樣例。

1. os.system

這是最簡單的一種方法,其執行過程中會輸出顯示cmd命令執行的信息。
注:該函數經常會出現錯誤,但是直接執行命令並沒有問題,所以一般建議不要使用。(引自:https://blog.csdn.net/bcfdsagbfcisbg/article/details/78134172)我目前還未遇到類似的情況。

Python的官方文檔指出:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

即官方推薦使用subprocess模塊。

代碼樣例:

#新開一個終端並運行本目錄下的test.sh文件
os.system("gnome-terminal -e 'bash -c \"./test.sh; exec bash\"'")
#運行本目錄下webVideoPlay.py程序
os.system("python3 webVideoPlay.py")
#關閉運行中的webVideoPlay.py程序
os.system("tmp=`ps -ef | grep webVideoPlay.py| grep -v grep | awk '{print $2}'`;echo ${tmp};kill -9 ${tmp}")

2. os.popen

以下引用官方原文:

Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is ‘r’ (default) or ‘w’. The buffering argument has the same meaning as the corresponding argument to the built-in open() function. The returned file object reads or writes text strings rather than bytes.
The close method returns None if the subprocess exited successfully, or the subprocess’s return code if there was an error.

翻譯如下:

打開到命令cmd或來自命令cmd的管道。返回值是連接到管道的打開的文件對象,可以根據模式是“ r”(默認)還是“ w”來進行讀取或寫入。緩衝參數與內置open()函數的相應參數含義相同。返回的文件對象讀取或寫入文本字符串,而不是字節。
如果subprocess成功退出,則close方法返回None;如果發生錯誤,則返回subprocess的返回代碼。

並且文檔還指出:
This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.
即os.popen來源於subprocess.Popen。所以我們即將總結的方法可能是最好的方法。

3. subprocess.Popen

引自Python官方文檔:

模塊的底層的進程創建與管理由 Popen 類處理。它提供了很大的靈活性,因此開發者能夠處理未被便利函數覆蓋的不常見用例。
class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None, text=None)
在一個新的進程中執行子程序。在 POSIX,此類使用類似於 os.execvp() 的行爲來執行子程序。在 Windows,此類使用了 Windows CreateProcess() 函數。 Popen 的參數如下:
args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

Popen下的方法:

Popen.poll()
檢查子進程是否已被終止。設置並返回 returncode 屬性。否則返回 None。

Popen.wait(timeout=None)
等待子進程被終止。設置並返回 returncode 屬性。如果進程在 timeout 秒後未中斷,拋出一個 TimeoutExpired 異常,可以安全地捕獲此異常並重新等待。

Popen.communicate(input=None, timeout=None)
與進程交互:向 stdin 傳輸數據。從 stdout 和 stderr 讀取數據,直到文件結束符。等待進程終止。可選的 input 參數應當未被傳輸給子進程的數據,如果沒有數據應被傳輸給子進程則爲 None。如果流以文本模式打開, input 必須爲字符串。否則,它必須爲字節。

Popen.send_signal(signal)
將信號 signal 發送給子進程。

Popen.terminate()
停止子進程。在 Posix 操作系統上,此方法發送 SIGTERM。在 Windows,調用 Win32 API 函數 TerminateProcess() 來停止子進程。

Popen.kill()
殺死子進程。在 Posix 操作系統上,此函數給子進程發送 SIGKILL 信號。在 Windows 上, kill() 是 terminate() 的別名。

代碼示例:

#運行本目錄下webVideoPlay.py程序
homedir = os.getcwd()
objectpath = str(homedir) + "/webVideoPlay.py"
print(objectpath)
returnCode = subprocess.Popen(["python3",objectpath])
time.sleep(10)
#關閉運行中的webVideoPlay.py程序
returnCode.kill()
#播放一段音頻並不顯示cmd命令執行的信息
returnCode = subprocess.Popen(["gst-play-1.0", play_path], stdout=subprocess.PIPE)
time.sleep(3)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章