Skip to main content
 首页 » 编程设计

Python 执行Shell命令

2022年07月19日196bonelee

Python 执行Shell命令

实际应用中可能需要在程序中执行一些shell命令,例如在Pycharm开发环境中,提交代码至github。我们知道传输文件是通过git命令,其一般在命令行中执行,所以Pycharm后台通过执行shell进行实现。本文通过示例学习Python执行基本shell命令方法。

1. Python os.system() 函数

os.system()函数可以执行系统命令,官方文档描述如下:
通过调用标准C函数system()实现,对应限制也一样。
然而命令有任何输出,会发送至解释器标准输出流,因此不建议使用。
下面示例获取git对应版本,使用命令git --version

import os 
 
cmd = "git --version" 
 
returned_value = os.system(cmd)  # returns the exit code in unix 
print('returned value:', returned_value) 
 

下面输出是在安装了git的ubuntu上:

git version 2.14.2 
returned value: 0 

注意我们没有将git版本命令输出打印到控制台,而是将其打印出来,因为控制台是这里的标准输出流,但实际输出没有获取到版本对应的值。

2. Python subprocess.call() 函数

前节中我们使用os.system()函数,本节我们看看subprocess模块的call函数执行系统命令。下面示例重写了上面的代码:

import subprocess 
 
cmd = "git --version" 
 
returned_value = subprocess.call(cmd, shell=True)  # returns the exit code in unix 
print('returned value:', returned_value) 
 

执行后输出结果与上节示例一样。

3. Python subprocess.check_output()函数

我们看前面两个方法不能操作这些命令的执行输出结果。本节介绍subprocess.check_output()函数,其可以保存输出结果到变量中。请看示例:

import subprocess 
 
cmd = "date" 
 
# returns output as byte string 
returned_output = subprocess.check_output(cmd) 
 
# using decode() function to convert byte string to string 
print('Current date is:', returned_output.decode("utf-8")) 

执行输出结果如下:

Sun Sep 29 18:31:57 CST 2019 

4. 总结

我们一共介绍了三种方式执行shell命令,但只有subprocess.check_output()函数可以获取输出结果。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/101708094