Python 如何在 Windows 中使用子进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19819417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Subprocess in Windows
提问by AHuman
I am trying to save the result or function runcmdin the variable Result. Here is what I have tried: import subprocess
我试图将结果或函数runcmd保存在变量Result 中。这是我尝试过的:导入子流程
def runcmd(cmd):
x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Result = x.communicate(stdout)
return Result
runcmd("dir")
When I run ths code, I get this result:
当我运行这些代码时,我得到了这个结果:
Traceback (most recent call last):
File "C:\Python27\MyPython\MyCode.py", line 7, in <module>
runcmd("dir")
File "C:\Python27\MyPython\MyCode.py", line 4, in runcmd
x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
What could I do to fix this?
我能做些什么来解决这个问题?
采纳答案by Chad Dienhart
I think what you are looking for is os.listdir()
我想你要找的是 os.listdir()
check out the os modulefor more info
查看os 模块以获取更多信息
an example:
一个例子:
>>> import os
>>> l = os.listdir()
>>> print (l)
['DLLs', 'Doc', 'google-python-exercises', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.e
xe', 'README.txt', 'tcl', 'Tools', 'VS2010Cmd.lnk']
>>>
You could also read the output into a list:
您还可以将输出读入列表:
result = []
process = subprocess.Popen('dir',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
result.append(line)
errcode = process.returncode
for line in result:
print(line)
回答by Erik Kaplun
As far as I know, diris a built in command of the shellin Windows and thus not a file available for execution as a program. Which is probably why subprocess.Popencannot find it. But you can try adding shell=Trueto the Popen()construtor call like this:
据我所知,dir是Windows 中shell的内置命令,因此不是可作为程序执行的文件。这可能就是为什么subprocess.Popen找不到它。但是您可以尝试像这样添加shell=True到Popen()构造函数调用中:
def runcmd(cmd):
x = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
return x.communicate(stdout)
runcmd("dir")
If shell=Truedoesn't help, you're out of luck executing dirdirectly. But then you can make a .batfile and put a call to dirthere instead, and then invoke that .batfile from Python instead.
如果shell=True没有帮助,那么dir直接执行就不走运了。但是,您可以创建一个.bat文件并dir调用该.bat文件,然后从 Python调用该文件。
btw also check out the PEP8!
顺便说一句,还请查看PEP8!
P.SAs Mark Ransom pointed out in a comment, you could just use ['cmd', '/c', 'dir']as the value of cmdinstead of the .bathack if shell=Truefails to fix the issue.
PS正如 Mark Ransom 在评论中指出的那样,如果无法解决问题,您可以仅使用代替hack['cmd', '/c', 'dir']的值。cmd.batshell=True

