Python 子进程 FileNotFoundError

Python subprocess FileNotFoundError

我正在尝试按照 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 like dir or passing arguments to 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 脚本路径中这可能是问题)