Use subprocess.Popen class in Python

subprocess.Popen 是 Python 标准库提供的一个类,用于进程的创建、管理以及数据交互。在实现上,它尽可能地屏蔽了操作系统之间相关语义的差异,提供了统一的使用接口。

其原型是:

class subprocess.Popen(args, bufsize=0, executable=None,
                       stdin=None, stdout=None, stderr=None,
                       preexec_fn=None, close_fds=False,
                       shell=False, cwd=None, env=None,
                       universal_newlines=False,
                       startupinfo=None, creationflags=0)

对于 args 参数,使用时遇到了这样的问题:

p = subprocess.Popen(r"ls --help")

运行时提示这样的错误信息:

Traceback (most recent call last):
  File "./test.py", line 12, in <module>
    main()
  File "./test.py", line 8, in main
    p = subprocess.Popen(r"ls --help")
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

关于 args,subprocess.Popen 的文档里有这样的描述:

On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.

所以这样修改后可以正常运行:

p = subprocess.Popen([r"ls", r"--help"])

另外,需要特别注意 shell 这个参数,默认为 False。如果为 True 的话:

  • Unix: 相当于 args 前面添加了 "/bin/sh" "-c"
  • Windows: 相当于添加 "cmd.exe /c"

Read More: