Python:使用os模块执行cmd命令

大家好,我是wangzirui32,今天我们来学习如何让Python执行cmd命令。
很简单,输入代码:

from os import system
# 在system里放入需要执行的命令即可 这里我写的是ipconfig命令
ok = system("ipconfig")
# 函数执行后如果没有错误则返回0 否则返回1
print(ok)

运行代码,即可执行cmd命令。
如果你想获取执行命令后返回的内容,可以使用popen函数:

from os import popen
# 在popen里放入需要执行的命令即可 这里我写的是ipconfig命令
text = popen("ipconfig").read()
print(text)

这样就完成了,你学会了吗?

猜你喜欢

转载自blog.csdn.net/wangzirui32/article/details/114789046