Python子进程FileNotFoundError异常

3
我是一名有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:

我正在尝试按照此博客中的说明从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)

这给了我一个错误:
文件未找到:[WinError 2] 系统找不到指定的文件
我阅读了很多关于这个错误的 SO 帖子,在大多数情况下,它似乎是 尝试调用系统命令(如dir)或将参数传递给check_output顺序错误的问题,但在我的情况下,我真的看不出哪里可能出错。
按照一些建议, 我尝试构建一个字符串 cmd 而不是列表,然后使用参数 shell = True 将其传递给 check_output - 当我这样做时,我会得到一个 CalledProcessError: returned non-zero exit status 1.

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

有人能帮忙吗?

以下是堆栈跟踪:

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

请问您能否提供您的错误堆栈信息? - hshantanu
在你的堆栈错误跟踪中,有没有调用过这个方法?"NamedTemporaryFile()" - hshantanu
1
你应该尝试使用正斜杠(/) - path2script = os.getcwd() + "/max.R" - Mortz
1个回答

2

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

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

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

就是这样!我刚刚发现我的“\bin”在最终字符串中变成了一个特殊字符(退格?)。在command字符串中像这样转义反斜杠:“\bin”解决了这个问题... - Tom Wagstaff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接