Python子流程FileNotFoundError

时间:2018-12-04 19:02:37

标签: python subprocess rscript file-not-found

我正在尝试遵循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]系统找不到指定的文件

我已经阅读了很多有关此错误的SO帖子,在大多数情况下,trying to invoke system commands似乎是一个问题,例如dir或将参数传递给check_output {{3} },但就我而言,我真的看不出怎么回事。

in the wrong order之后,我尝试为cmd而不是列表创建一个字符串,然后使用参数check_output将其传递给shell = True-当我这样做时我得到一个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

1 个答案:

答案 0 :(得分:1)

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

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

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