1

子进程模块的文档声明“如果shell为 True,则将通过 shell 执行指定的命令”。在 Windows 操作系统上,这在实践中意味着什么?

4

4 回答 4

3

这意味着该命令将使用COMSPEC环境变量中指定的程序执行。通常cmd.exe.

确切地说,子进程调用windows api函数,作为参数CreateProcess传递。"cmd.exe /c " + argslpCommandLine

如果 shell==False,lpCommandLineCreateProcess 的参数就是args.

于 2009-04-21T09:39:22.687 回答
1

当你执行一个外部进程时,你想要的命令可能看起来像“foo arg1 arg2 arg3”。如果“foo”是一个可执行文件,那就是执行并给出参数的内容。

但是,通常情况下,“foo”实际上是某种脚本,或者可能是 shell 内置的命令,而不是磁盘上的实际可执行文件。在这种情况下,系统不能直接执行“foo”,因为严格来说,这类事情是不可执行的。他们需要某种“外壳”来执行它们。在 *nix 系统上,这个 shell 通常(但不一定)是 /bin/sh。在 Windows 上,它通常是 cmd.exe(或存储在 COMSPEC 环境变量中的任何内容)。

这个参数允许你定义你希望使用什么 shell 来执行你的命令,对于相对罕见的情况,当你不想要默认值时。

于 2009-04-21T14:04:08.057 回答
0

using-the-subprocess-module中,有一个明确的段落:

可执行参数指定要执行的程序。很少需要它:通常,要执行的程序由 args 参数定义。如果 shell=True,可执行参数指定使用哪个 shell。在 Unix 上,默认的 shell 是 /bin/sh。在 Windows 上,默认 shell 由 COMSPEC 环境变量指定。

Windows 示例- 没有 shell将无法识别shell ( cmd.exe) 命令:date -t

>>> p=subprocess.Popen(["date", "/t"], stdout=subprocess.PIPE)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python26\lib\subprocess.py", line 595, in __init__
    errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 804, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> 

使用外壳,一切都很好:

>>> p=subprocess.Popen(["date", "/t"], shell=True, stdout=subprocess.PIPE)
>>> p.communicate()
('Wed 04/22/2009 \r\n', None)
>>>
于 2009-04-21T09:43:28.527 回答
0

除了其他答案中所说的之外,如果您想在该文件类型的默认查看器中打开文件,这在实践中很有用。例如,如果您想打开 HTML 或 PDF 文件,但不知道将运行它的系统上安装了哪个浏览器或查看器,或者无法保证可执行文件的路径,您可以简单地传递文件名作为 args 字段的唯一参数,然后设置 shell=True。这将使 Windows 使用与该文件类型关联的任何程序。需要注意的是,如果文件路径有空格,则需要用两个 ".

例如。

path = "C:\\Documents and Settings\\Bob\\Desktop\\New Folder\\README.txt"
subprocess.call('""' + path + '""', shell = True)
于 2009-04-21T13:51:24.407 回答