我找了好久还是没搞明白... 这是我的部分代码出错的地方。
import subprocess as sp
import os
cmd_args = []
cmd_args.append('start ')
cmd_args.append('/wait ')
cmd_args.append(os.path.join(dirpath,filename))
print(cmd_args)
child = sp.Popen(cmd_args)
还有命令提示符。
['start ', '/wait ', 'C:\\Users\\xxx\\Desktop\\directory\\myexecutable.EXE']
Traceback (most recent call last):
File "InstallALL.py", line 89, in <module>
child = sp.Popen(cmd_args)
File "C:\Python34\lib\subprocess.py", line 859, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1114, in _execute_child startupinfo)
FileNotFoundError: [WinError 2]
看起来文件路径有 2 个反斜杠是错误的。
我知道如果我这样做
print(os.path.join(dirpath,filename))
它会回来
C:\Users\xxx\Desktop\directory\myexecutable.EXE
我确定文件就在那里。 我该如何调试?
最佳答案
发生这种情况是因为 Popen
正在尝试查找文件 start
而不是您要运行的文件。
例如,使用notepad.exe
:
>>> import subprocess
>>> subprocess.Popen(['C:\\Windows\\System32\\notepad.exe', '/A', 'randomfile.txt']) # '/A' is a command line option
<subprocess.Popen object at 0x03970810>
这很好用。但是如果我把路径放在列表的末尾:
>>> subprocess.Popen(['/A', 'randomfile.txt', 'C:\\Windows\\System32\\notepad.exe'])
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
subprocess.Popen(['/A', 'randomfile.txt', 'C:\\Windows\\System32\\notepad.exe'])
File "C:\python35\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\python35\lib\subprocess.py", line 1220, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
改用这个:
import subprocess as sp
import os
cmd_args = []
cmd_args.append(os.path.join(dirpath,filename))
cmd_args.append('start ')
cmd_args.append('/wait ')
print(cmd_args)
child = sp.Popen(cmd_args)
您可能还需要交换 cmd_args.append('start ')
和 cmd_args.append('/wait ')
,具体取决于它们的顺序在。
关于python:Popen FileNotFoundError 的问题:[WinError 2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39269675/