Skip to main content
 首页 » 编程设计

Python 子进程 FileNotFoundError

2024年12月31日8kuangbin

我正在尝试关注 this blog关于如何从 Python 执行 R 脚本。我使用 Rscript 从命令行运行 R 脚本。

这是我的 Python 代码:

import subprocess 
import os 
 
command = "C:\Program Files\R\R-3.4.4\bin\Rscript" 
path2script = os.getcwd() + "\max.R" # gives me the absolute path to the R script 
args = ["11", "3", "9", "42"] 
 
cmd = [command, path2script] + args 
x = subprocess.check_output(cmd, universal_newlines = True) 

这给了我这个错误:

FileNotFoundError: [WinError 2] The system cannot find the file specified

我已经阅读了很多关于此错误的 SO 帖子,在大多数情况下,这似乎是 trying to invoke system commands 的问题。像 dir 或将参数传递给 check_output in the wrong order但就我而言,我真的看不出哪里出了问题。

正在关注 some of the advice我试过为 cmd 而不是列表构建一个字符串,然后使用参数 shell = True 将它传递给 check_output - 当我这样做我得到一个 CalledProcessError: returned non-zero exit status 1.

我假设这段代码,除了添加文件的绝对路径之外,与它在博客上出现的完全一样,现在失败了,因为 check_output 的行为自 2015 年以来发生了变化。 .

有人能帮忙吗?

这是堆栈跟踪:

Traceback (most recent call last): 
 
  File "<ipython-input-2-3a0151808726>", line 1, in <module> 
    runfile('C:/Users/TomWagstaff/Documents/Raising IT/Projects/15 AdWords/Python_R_test/run_max.py', wdir='C:/Users/TomWagstaff/Documents/Raising IT/Projects/15 AdWords/Python_R_test') 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile 
    execfile(filename, namespace) 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile 
    exec(compile(f.read(), filename, 'exec'), namespace) 
 
  File "C:/Users/TomWagstaff/Documents/Raising IT/Projects/15 AdWords/Python_R_test/run_max.py", line 31, in <module> 
    x = subprocess.check_output(cmd, universal_newlines = True) 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\subprocess.py", line 336, in check_output 
    **kwargs).stdout 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\subprocess.py", line 403, in run 
    with Popen(*popenargs, **kwargs) as process: 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\site-packages\spyder\utils\site\sitecustomize.py", line 210, in __init__ 
    super(SubprocessPopen, self).__init__(*args, **kwargs) 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\subprocess.py", line 709, in __init__ 
    restore_signals, start_new_session) 
 
  File "C:\Users\TomWagstaff\Anaconda3\envs\adwords\lib\subprocess.py", line 997, in _execute_child 
    startupinfo) 
 
FileNotFoundError: [WinError 2] The system cannot find the file specified 

请您参考如下方法:

检查命令和脚本的路径是否正确

print(os.path.exists(command)) 
print(os.path.exists(path2script)) 

请注意,使用反斜杠编写路径可能很危险,因为您可以用这种方式创建转义序列,而转义序列将以不同的方式进行解释。您可以使用正斜杠编写 Windows 路径,然后在其上调用 os.path.normpath,将它们转换为安全形式 (同样在命令中你只能使用正斜杠,Python 解释并不关心。在你的 R 脚本的路径中这可能是问题)