【问题标题】:python: trouble with Popen FileNotFoundError: [WinError 2]python:Popen FileNotFoundError 的问题:[WinError 2]
【发布时间】:2016-09-01 10:57:01
【问题描述】:

我找了好久还是没搞明白... 这是我出错的部分代码。

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

我确定文件在那里。 我该如何调试?

【问题讨论】:

  • 需要第一个反斜杠来转义第二个反斜杠,所以双反斜杠不是问题
  • 你也可以试试shell=True吗?
  • 路径正确。双反斜杠不是问题,它们是字符串的repr 的产物。无论如何:您确定问题是最后一个参数而不是startstartcommand 还是内置的 shell?
  • @Idos 请注意,仅添加 shell=True 不会产生预期的结果。您必须使用单个字符串参数来表示命令行,而不是传递 shell=True 时的参数列表,即 Popen('start /wait &lt;the-path&gt;', shell=True)
  • 非常感谢大家。 Bakuriu的回答奏效了。事实上,我应该将我的论点作为字符串而不是列表传递。

标签: python


【解决方案1】:

发生这种情况是因为 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 '),具体取决于它们的顺序。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,只是添加一个关于 Popen 的注释:作为参数,Popen 需要一个用于非 shell 调用的字符串列表,而只有一个用于 shell 调用的字符串。

    此处列出的详细信息:WinError 2 The system cannot find the file specified (Python)

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多