Python系统命令– os.system(),subprocess.call()

时间:2020-02-23 14:43:35  来源:igfitidea点击:

在本教程中,我们将学习Python系统命令。

Python系统命令

使用python编写程序时,可能需要为程序执行一些shell命令。
例如,如果您使用PycharmIDE,您可能会注意到可以在github上共享您的项目。
您可能知道文件传输是通过git完成的,而git是使用命令行操作的。
因此,Pycharm在后台执行一些shell命令来执行此操作。

但是,在本教程中,我们将学习一些有关从python代码执行shell命令的基础知识。

Python os.system()函数

我们可以使用os.system()函数执行系统命令。
根据官方文件,据说

<p>This is implemented by calling the Standard C function system(), and has the same limitations.</p>

但是,如果命令生成任何输出,则将其发送到解释器标准输出流。
不建议使用此命令。
在下面的代码中,我们将尝试使用系统命令git --version来了解git的版本。

import os

cmd = "git --version"

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

在已安装git的ubuntu 16.04中找到以下输出。

git version 2.14.2
returned value: 0

请注意,由于控制台是此处的标准输出流,因此我们不会将git version命令输出打印到控制台,而是将其打印出来。

Python subprocess.call()函数

在上一节中,我们看到os.system()函数可以正常工作。
但是不建议您执行Shell命令。
我们将使用Python子进程模块执行系统命令。

我们可以使用subprocess.call()函数运行shell命令。
请参见以下代码,该代码与先前的代码等效。

import subprocess

cmd = "git --version"

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

并且输出也将相同。

Python subprocess.check_output()函数

到目前为止,我们已经在python的帮助下执行了系统命令。
但是我们无法操纵这些命令产生的输出。
使用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"))

它将产生如下输出

Current date is: Thu Oct  5 16:31:41 IST 2016