如何在Python 2.7中调用指定的PowerShell脚本?
Hey there! Let's get that PowerShell script running from your Python 2.7 code smoothly. Since you already know the manual command, translating that to Python is straightforward using the built-in subprocess module—here are a couple of solid approaches:
Basic Execution (No Output Capture)
If you just need to run the script and don't care about capturing its output or errors, this simple method works perfectly:
import subprocess # Use a list of arguments to avoid quoting issues subprocess.call(['powershell', '-Command', r'C:\shellcommand.ps1'])
Notice the r prefix on the path string? That's a raw string in Python, which lets you use single backslashes without escaping them—way cleaner than writing C:\\shellcommand.ps1.
Capture Output and Handle Errors
If you want to check if the script ran successfully or log its output, use check_output instead. This will throw an error if the PowerShell script fails, and let you access both stdout and stderr:
import subprocess try: # Capture both standard output and error streams script_output = subprocess.check_output( ['powershell', '-Command', r'C:\shellcommand.ps1'], stderr=subprocess.STDOUT, shell=False ) print("Script executed successfully! Output:\n{}".format(script_output)) except subprocess.CalledProcessError as e: print("Script failed with exit code {}!".format(e.returncode)) print("Error details:\n{}".format(e.output))
Troubleshooting Tips
- Execution Policy Issues: If you hit a "script cannot be loaded because running scripts is disabled on this system" error, add the
-ExecutionPolicy Bypassflag to your PowerShell command:subprocess.call(['powershell', '-ExecutionPolicy', 'Bypass', '-Command', r'C:\shellcommand.ps1']) - Admin Permissions: If your script requires admin rights, make sure you launch your Python script with administrator privileges—there's no easy way to elevate permissions from within Python itself without extra workarounds.
内容的提问来源于stack exchange,提问作者Sravani Chinta

