Running powershell script within python script, how to make python print the powershell output while it is running

后端 未结 2 1728
青春惊慌失措
青春惊慌失措 2020-11-29 04:01

I am writing a python script which checks various conditions and runs a powershell script accordingly to help me automate migration from windows XP to windows 7. The powersh

相关标签:
2条回答
  • 2020-11-29 04:33
    1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

      Set-ExecutionPolicy RemoteSigned
      
    2. 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()
      

    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
    
    0 讨论(0)
  • 2020-11-29 04:33

    I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

    >>> import subprocess
    >>> import sys
    >>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
    >>> Hello World
    _
    0 讨论(0)
提交回复
热议问题