【问题标题】:WinError 2: File not found with Subprocess.runWinError 2:未使用 Subprocess.run 找到文件
【发布时间】:2019-12-06 13:47:16
【问题描述】:

版本:Python 3.7.5

操作系统:Windows 10

我正在尝试修复以下“找不到文件”错误。 python代码如下所示,后面是命令行产生的错误。

Python:

    subprocess.run(['start', 'current_roster.xlsx'], check=True)

找不到文件错误:

 Traceback (most recent call last):
   File "__winmain__.py", line 569, in <module>
     update_roster()
   File "__winmain__.py", line 480, in update_roster
     subprocess.run(['start', 'current_roster.xlsx'], check=True)
   File "C:\Python37\lib\subprocess.py", line 488, in run
     with Popen(*popenargs, **kwargs) as process:
   File "C:\Python37\lib\subprocess.py", line 800, in __init__
     restore_signals, start_new_session)
   File "C:\Python37\lib\subprocess.py", line 1207, in _execute_child
     startupinfo)
 FileNotFoundError: [WinError 2] The system cannot find the file specified

我在 OSX 上也有上述脚本的代码,它是功能性的,但使用“打开”命令代替“开始”。它不会产生上述错误。

默认情况下 subprocess.run() 不查找当前工作目录中的指定文件吗?尝试时我也遇到同样的错误:

    cwd = os.path.abspath(sys.argv[0])
    cwd = os.path.dirname(cwd)
    filepath = os.path.join(cwd, 'current_roster.xlsx')
    subprocess.run(['start', filepath], check = True)

【问题讨论】:

  • 最好使用 .xlsx 文件的绝对路径。
  • 试试subprocess.run(['start', 'current_roster.xlsx'], shell=True, check=True)
  • @facehugger 这行得通!如果我希望它从 python 到带有 PyInstaller 之类的可执行文件,这对于我发送给它的用户来说仍然是完全可用的吗?

标签: python windows subprocess


【解决方案1】:

错误并不是说找不到参数。意思是找不到start 命令,因为它是internal command。您只能从cmd.exe 使用它。

您可以使用@facehugger 在评论中建议的更改来解决此问题:

试试subprocess.run(['start', 'current_roster.xlsx'], shell=True)

【讨论】:

  • 我明白了。如果我希望它成为可分发的 python .exe,那么正确的约定是什么?
  • 如果我希望它从 python 到带有 PyInstaller 之类的可执行文件,这对于我发送给它的用户是否仍然完全可用?
  • @Xonu 你需要测试它,但它应该是。
猜你喜欢
  • 2021-09-15
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
相关资源
最近更新 更多