Python调用Windows命令行执行R脚本失败,求解决办法
Let's break down why your R script isn't running via Python and fix it step by step.
Diagnosing Your Existing Approaches
Problem with Method 1
Your first attempt uses subprocess.Popen([command,script], shell=True) but fails to execute the script. Here's the likely cause:
- When
shell=Trueis enabled on Windows, it invokescmd.exe, but Spyder's environment might not haveRscriptin its system PATH (even if it works in your regular command prompt). The shell can't locate the executable, so the process fails silently. - The "1" you see in the console is probably the spawned process's ID (PID), not an error code. You're also not waiting for the process to finish or capturing errors, so you can't tell what's going wrong.
Problem with Method 2
Your second command includes --vanilla -q -f, but the issue is likely how you're formatting the command string. If either the Rscript.exe path or your script path has spaces (a common pitfall even if yours don't now), the shell will misinterpret the command. Without capturing error output, you can't see why it's failing.
Quick breakdown of those Rscript flags:
--vanilla: Starts R with a clean environment—no user config files (like.Rprofile) loaded, no saved workspace restored. This prevents unexpected behavior from custom settings.-q: Runs in "quiet" mode, suppressing R's startup welcome messages.-f: Tells R to execute the specified script file (this is redundant if you pass the script path directly toRscript, since that's its default behavior).
The Reliable Solution
Here's a tested way to run your R script from Python, with error checking and completion confirmation:
import subprocess import os # Use absolute paths to eliminate ambiguity # Replace with your actual Rscript.exe path (check your R installation directory) rscript_path = "C:/Program Files/R/R-3.5.2/bin/Rscript.exe" script_path = os.path.abspath("C:/Path/to/test_script.R") # Run the script and capture output/errors proc = subprocess.Popen( [rscript_path, "--vanilla", "-q", script_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True # Directly decode output to string (works in Python 3.7+) ) # Wait for the process to finish and retrieve results stdout, stderr = proc.communicate() return_code = proc.returncode # Check if the script ran successfully if return_code == 0: print("R script executed successfully!") # Optional: Uncomment to view script output # print("Script output:", stdout) else: print(f"R script failed with return code {return_code}") print("Error details:", stderr)
Key Fixes & Best Practices
- Use absolute paths: Always specify the full path to
Rscript.exeand your R script. This avoids PATH-related issues in Spyder's isolated environment. - Avoid
shell=Truewhen possible: Passing a list of arguments (instead of a single string) is safer and prevents shell parsing errors, especially with spaces in paths. - Capture output and errors: Using
stdout=subprocess.PIPEandstderr=subprocess.PIPElets you see exactly what's happening—whether the script fails to start, or the R code itself has bugs. - Wait for completion:
communicate()waits for the process to finish, so you know exactly when the script is done running.
If you still run into issues:
- Double-check that your R script runs correctly in the command line using the exact paths from the Python code.
- Verify that the user running Spyder has write permissions to the directory where the script should generate files.
内容的提问来源于stack exchange,提问作者schm1651

