AHu*_*man 6 python windows subprocess pipe
我试图在变量Result中保存结果或函数runcmd.这是我尝试过的:import subprocess
def runcmd(cmd):
x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Result = x.communicate(stdout)
return Result
runcmd("dir")
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我得到了这个结果:
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
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能解决这个问题?
Cha*_*art 15
我认为你要找的是os.listdir()
查看os模块了解更多信息
一个例子:
>>> 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']
>>>
Run Code Online (Sandbox Code Playgroud)
您还可以将输出读入列表:
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)
Run Code Online (Sandbox Code Playgroud)
据我所知,它dir是Windows中内置的shell命令,因此不是可以作为程序执行的文件.这可能是为什么subprocess.Popen找不到它.但你可以尝试添加shell=True这样的Popen()construtor调用:
def runcmd(cmd):
x = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
return x.communicate(stdout)
runcmd("dir")
Run Code Online (Sandbox Code Playgroud)
如果shell=True没有帮助,你就不能dir直接执行了.但是你可以创建一个.bat文件并在dir那里调用,然后.bat从Python 调用该文件.
PS检查PEP8也:)例如局部变量应该以Python中的小写字母开头(即['cmd', '/c', 'dir']=> cmd).
PPS正如Mark Ransom在评论中指出的那样,如果无法解决问题,你可以将其.bat用作shell=True代替dir黑客的价值subprocess.Popen.
| 归档时间: |
|
| 查看次数: |
22930 次 |
| 最近记录: |