相关文章推荐
谈吐大方的水龙头  ·  python去掉空白行的两种代码实现_pyt ...·  14 小时前    · 
腹黑的橡皮擦  ·  python写入文件时多余空行问题·  14 小时前    · 
满身肌肉的小刀  ·  Python去掉文件中空行_python不空行·  14 小时前    · 
爱健身的杯子  ·  Python写入csv文件时出现空行_为什么 ...·  14 小时前    · 
瘦瘦的棒棒糖  ·  python剔除空行 - ·  14 小时前    · 
耍酷的蘑菇  ·  动漫产业占日本GDP的比重超过10%,相当于 ...·  8 月前    · 
大气的书包  ·  新闻当事人 黄宏-搜狐新闻·  9 月前    · 
才高八斗的茄子  ·  全国政协十二届四次会议专题--中国政协新闻网 ...·  9 月前    · 
温柔的汉堡包  ·  “井打到哪裡,鐵人精神就帶到哪裡”--黨史- ...·  10 月前    · 
威武的钥匙扣  ·  市政府关于授予肖颖等同志见义勇为称号和表彰见 ...·  1 年前    · 
Code  ›  Executing PowerShell from Python • Jamie Phillips
info syntax python
https://www.phillipsj.net/posts/executing-powershell-from-python/
安静的香菇
6 天前
Skip to Main Menu

  • Home
  • About
  • Buy me a coffee
  • Projects
  • Podcasts
  • Talks
  • Sessionize
  • Archives
  • Tags
Skip to Content Toggle Sidebar

Jamie Phillips

Executing PowerShell from Python

Posted on 2020-10-25 3 mins read

I have an experiment that I am working on and thought that leveraging Python would be fun. As part of that experiment, I would need to execute PowerShell from Python since only PowerShell cmdlets are available to do what I need. After a little research a week of letting it simmer, I was able to sit down the last night and work it out. Part of it is my unfamiliarity with Python for what I am doing, and the other part is just me not thinking about the problem holistically.

What you need

You will need PowerShell installed on your system and Python 3.6+. This would work cross-platform. I did my testing on Kubuntu 20.10 running PowerShell as a snap package. You will not need any external libraries since we use one of the many great libraries that ship out of the box with Python.

The code

All we need is to create a file call ps.py , and then we can import the subprocess module.

import subprocess

Now we can make our run method that we will use to execute our PowerShell command.

def run(self, cmd):
    completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
    return completed

Let’s make our Python file executable and then create the commands we want to execute. One command has the correct syntax, and one command has bad syntax. This will demonstrate how to use the return of the subprocess.run method.

if __name__ == '__main__':
    hello_command = "Write-Host 'Hello Wolrd!'"
    hello_info = run(hello_command)
    if hello_info.returncode != 0:
        print("An error occured: %s", hello_info.stderr)
    else:
        print("Hello command executed successfully!")
    print("-------------------------")
    bad_syntax_command = "Write-Hst 'Incorrect syntax command!'"
    bad_syntax_info = run(bad_syntax_command)
    if bad_syntax_info.returncode != 0:
        print("An error occured: %s", bad_syntax_info.stderr)
    else:
        print("Bad syntax command executed successfully!")

Here is the complete file.

import subprocess
def run(self, cmd):
    completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
    return completed
if __name__ == '__main__':
    hello_command = "Write-Host 'Hello Wolrd!'"
    hello_info = run(hello_command)
    if hello_info.returncode != 0:
        print("An error occured: %s", hello_info.stderr)
    else:
        print("Hello command executed successfully!")
    print("-------------------------")
    bad_syntax_command = "Write-Hst 'Incorrect syntax command!'"
    bad_syntax_info = run(bad_syntax_command)
    if bad_syntax_info.returncode != 0:
        print("An error occured: %s", bad_syntax_info.stderr)
    else:
        print("Bad syntax command executed successfully!")

Execute ps.py , and we can see the output. The first command didn’t fail and returned an exit code of zero, and we print that it ran successfully. The second command has a typo, and we get an exit code of one that we then print the error that came from standard error.

$ python ps.py
Hello command executed successfully!
-------------------------
 
推荐文章
谈吐大方的水龙头  ·  python去掉空白行的两种代码实现_python word页眉减少一行空白
14 小时前
腹黑的橡皮擦  ·  python写入文件时多余空行问题
14 小时前
满身肌肉的小刀  ·  Python去掉文件中空行_python不空行
14 小时前
爱健身的杯子  ·  Python写入csv文件时出现空行_为什么csv文件里有数据,读入时为空
14 小时前
瘦瘦的棒棒糖  ·  python剔除空行 -
14 小时前
耍酷的蘑菇  ·  动漫产业占日本GDP的比重超过10%,相当于中国农业产值,为什么中国6.7农民的产值,日本人拍几部动漫_百度知道
8 月前
大气的书包  ·  新闻当事人 黄宏-搜狐新闻
9 月前
才高八斗的茄子  ·  全国政协十二届四次会议专题--中国政协新闻网--人民网
9 月前
温柔的汉堡包  ·  “井打到哪裡,鐵人精神就帶到哪裡”--黨史-中國共產黨新聞網
10 月前
威武的钥匙扣  ·  市政府关于授予肖颖等同志见义勇为称号和表彰见义勇为工作先进单位先进工作者的决定
1 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号