Python运行poweshell指令出错故障处理

项目场景:

`Python 在调用subprocess 模块运行管道指令出现故障无法运行,报 is not recognized as an internal or external command,operable program or batch file.


问题描述

当在Popen构造函数中添加cmd指令时工作正常,但在运行powershell指令时报警,显示
[指令] is not recognized as an internal or external command,operable program or batch file.


原因分析:

windows系统默认运行指令为CMD,并非powershell,所以在cmd运行powershell指令会报警


解决方案:

在Popen构造函数中加入运行程序,即powershell.exe; 如果仍有问题可能原因为系统环境变量未包含powershell.exe文件,可以在参数powershell.exe前面加上其文件路径。

from subprocess import Popen, PIPE

if __name__ == '__main__':
    print('hello')
    sub1 = Popen('ipconfig', stdin=None, stdout=PIPE, shell=True, text=True)
    sub2 = Popen('gal', stdin=None, stdout=PIPE, shell=True, text=True)# 这个指令无法运行因为默认是在cmd命令行中执行,无法识别
    sub3 = Popen('powershell.exe Get-NetAdapter', stdin=None, stdout=PIPE, shell=True, text=True)
    # print(str(sub1.communicate()))
    std1 = sub1.communicate()
    std2 = sub2.communicate()
    std3 = sub3.communicate()

    # print(std1[0] + '\n')
    print(std2[0]+ '\n')
    print(std2[1])
    print(std3[0])
    print(std3[1])

输出结果如下:

'gal' is not recognized as an internal or external command,
operable program or batch file.


None

Name                      InterfaceDescription                    ifIndex Statu
                                                                          s    
----                      --------------------                    ------- -----
Ethernet                  Intel(R) Ethernet Connection (4) I219-V      20 Di...
VirtualBox Host-Only N... VirtualBox Host-Only Ethernet Adapter        15 Up   
Wi-Fi                     Intel(R) Dual Band Wireless-AC 8265          13 Up   
VMware Network Adapte...1 VMware Virtual Ethernet Adapter for ...      12 Up   
VMware Network Adapte...8 VMware Virtual Ethernet Adapter for ...      10 Up   
Ethernet 2                OrayBoxVPN Virtual Ethernet Adapter           8 Di...
Bluetooth Network Conn... Bluetooth Device (Personal Area Netw...       4 Di...



None

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值