首页 > 解决方案 > WinError 2:未使用 Subprocess.run 找到文件

问题描述

版本: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)

标签: pythonwindowssubprocess

解决方案


该错误并不是说未找到该论点。start意思是找不到该命令,因为它是一个内部命令。您只能从cmd.exe.

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

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


推荐阅读