You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python 2.7中调用指定的PowerShell脚本?

Running a PowerShell Script from Python 2.7

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 Bypass flag 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:15:32