项目场景:
`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
本文探讨了Python在Windows环境下使用subprocess模块运行powershell指令时遇到的'isnotrecognized'错误,原因在于默认CMD不识别powershell。解决方法是通过Popen构造函数指定powershell.exe并确保系统路径包含它。实例展示了如何正确调用powershell获取网络适配器信息。

1062

被折叠的 条评论
为什么被折叠?



