在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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章