简体   繁体   中英

Why won't subprocess.run execute a simple command?

I run:

Rscript hello_world.R

from my cmd terminal where the directory is:

C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara>

The script runs fine.

However, I want Python to run it and have this small script located in the same directory as above:

import subprocess
subprocess.run(['Rscript', 'hello_world.R'])

However, I get this error when I run it from VS Code:

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

I next tried:

subprocess.run(['Rscript', 'hello_world.R'], shell=True)

But I got:

'Rscript' is not recognized as an internal or external command, operable program or batch file.

For reference I've added the following to my path:

C:\Program Files\R\R-3.6.3\bin\x64

I've just tried running

Rscript hello_world.R

from the cmd terminal in VS Code which has the following directory set:

(polgara) C:\Users\Philip\OneDrive\Betting\Capra\Tennis\polgara>

This also gives the error:

'Rscript' is not recognized as an internal or external command, operable program or batch file.

Could the (polgara) at the beginning be the source of my problem? I believe this is my virtual environment...?

Please take a look on:

What is the reason for "X is not recognized as an internal or external command, operable program or batch file"?

It is necessary to restart Windows after a modification of system environment variable Path to make sure all processes work with updated Path .

In general any executable can be run from within a Python script without the usage of Windows command processor cmd.exe which means without using shell=True . But it is necessary to specify the executable with full qualified file name, ie drive + path + name + extension, on not being in current directory of running process which is in this case python.exe interpreting the Python script.

I suggest to read the Microsoft documentation for function CreateProcessA and the other pages referenced on this page respectively listed on left side. All the parameters of the methods of Python module subprocess like cwd (current working directory for the subprocess) are easier to understand on having knowledge about process creation by Windows kernel.

The R script file name passed as argument to Rscript.exe should be specified also with full qualified file name to be found by Rscript.exe independent on what is the current directory of Rscript process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM