Python子进程在Windows 7上无法工作

0 投票
1 回答
3071 浏览
提问于 2025-04-21 04:14

有人能解释一下这里发生了什么吗?连内置的cmd.exe命令都不管用了:

Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call('dir')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python34\lib\subprocess.py", line 535, in call
    with Popen(*popenargs, **kwargs) as p:
  File "D:\Python34\lib\subprocess.py", line 848, in __init__
    restore_signals, start_new_session)
  File "D:\Python34\lib\subprocess.py", line 1104, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>>

1 个回答

6

要使用 'dir' 命令,你需要加上 shell=True

>>> import subprocess
>>> subprocess.call('dir', shell=True)

这样做的原因是因为 dir 是直接内置在命令行中的,它不是一个独立的程序。这一点在 subprocess.Popen文档 中也有提到:

在Windows系统中,当你设置 shell=True 时,COMSPEC环境变量会指定默认的命令行。在Windows上,只有当你想执行的命令是内置在命令行中的(比如 dir 或 copy)时,你才需要加上 shell=True 如果你要运行的是批处理文件或其他控制台程序,就不需要加这个选项。

撰写回答