且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python脚本中运行powershell脚本,如何让python在运行时打印powershell输出

更新时间:2023-02-03 20:57:43

  1. 确保您可以运行 powershell 脚本(默认情况下它是禁用的).很可能你已经这样做了.http://technet.microsoft.com/en-us/library/ee176949.aspx

Set-ExecutionPolicy RemoteSigned

  • 在你的powershell脚本helloworld.py上运行这个python脚本:

  • Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

  • 此代码基于 python3.4(或任何 3.x 系列解释器),但它也适用于 python2.x 系列.

    This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

    C:\Users\MacEwin\Desktop>python helloworld.py
    Hello World