[英]Using Python and external programs
By using python, how do I use cmd.exe supported commands and get the output to be viewed back in python? 通过使用python,如何使用cmd.exe支持的命令并获取要在python中查看的输出? The reason I am doing this is to get the Microsoft .NET framework version.
我这样做的原因是要获得Microsoft .NET Framework版本。 At the moment I could only find it through the cmd.exe by using the following command:
目前,我只能使用以下命令通过cmd.exe找到它:
wmic product where "Name like 'Microsoft .Net%'" get Name, Version
So I was thinking to get python to execute the above command and get the results back and write them to a file. 因此,我正在考虑让python执行上述命令并将结果返回并写入文件。
Here is a way about how to execute cmd command from python using the subprocess module. 这是一种有关如何使用subprocess模块从python执行cmd命令的方法。
Code : The following code is just pinging the loopback address using ping 127.0.0.1
command and then writing the results to a file. 代码 :以下代码仅使用
ping 127.0.0.1
命令ping回送地址,然后将结果写入文件。 Docs for file handling in python could be found here . 文档在Python中的文件处理可以找到这里 。
import subprocess
def myFunc():
p = subprocess.Popen("ping 127.0.0.1", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out
print err
with open('myOutputFile.txt', 'w') as f:
f.write(out) #Write the output to a file
myFunc()
Replace the ping 127.0.0.1
with other cmd command and it should work. 用其他cmd命令替换
ping 127.0.0.1
,它应该可以工作。 For eg: netstat -a
. 例如:
netstat -a
。
Note: It might take a while before you see the output in console, because the output will be returned to the console when the cmd command has finished the execution! 注意:在控制台中看到输出之前,可能要花一些时间,因为当cmd命令完成执行后,输出将返回到控制台!
The following code should do your job: 以下代码可以完成您的工作:
import subprocess
def myFunc():
p = subprocess.Popen("wmic product where \"Name like 'Microsoft .Net%'\" get Name, Version", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out
print err
with open('myOutputFile.txt', 'w') as f:
f.write(out) #Write the output to a file
myFunc()
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.