我试图将结果或函数runcmd保存在变量result中。 以下是我尝试过的: 导入子流程
def runcmd(cmd):
x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
Result = x.communicate(stdout)
return Result
runcmd("dir")
当我运行这些代码时,我得到这样的结果:
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
我能做些什么来解决这个问题?
我想你要找的是os.listdir()
查看os module了解更多信息
例如:
您还可以将输出读入列表:
据我所知,
dir
是Windows中shell的内置命令,因此不是作为程序执行的文件。这可能就是subprocess.Popen
找不到它的原因。但是您可以尝试将shell=True
添加到Popen()
construtor调用中,如下所示:如果
shell=True
没有帮助,那么直接执行dir
是不走运的。但是,您可以创建一个.bat
文件,然后在那里调用dir
,然后从Python调用该.bat
文件。顺便看看PEP8!
p.S正如Mark Ransom在一条评论中指出的,如果
shell=True
未能解决问题,您可以使用['cmd', '/c', 'dir']
作为cmd
的值,而不是.bat
的hack。相关问题 更多 >
编程相关推荐