Python 系统命令 - os.system()、subcess.call()

在本教程中,我们将学习关于Python系统命令. 之前,我们了解了关于 [Python 随机号码]( / 社区 / 教程 / python - 随机号码)。

Python 系统命令

例如,如果你使用‘Pycharm’ IDE,你可能会注意到有选择在github上共享你的项目,而且你可能知道文件传输是由 git进行的,这是使用命令行操作的。

Python OS 系统() 函数

我们可以使用 os.system()函数执行系统命令。

这是通过调用标准C函数系统()实现的,并且具有相同的局限性。

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

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

以下输出是在ubuntu 16.04 中找到的,那里已经安装了 git。

1git version 2.14.2
2returned value: 0

请注意,我们不会将 git 版本的命令输出打印到控制台,它正在被打印,因为控制台是这里的标准输出流。

Python subprocess.call() 函数

在上一节中,我们看到‘os.system()’函数运行得很好,但它不是执行壳命令的推荐方式,我们将使用Python subprocess模块执行系统命令,我们可以使用‘subprocess.call()’函数运行壳命令。

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

And the output will be same also. Python System Command

Python 的 subprocess.check_output() 函数

到目前为止,我们使用python执行了系统命令,但我们无法操纵这些命令产生的输出,使用subprocess.check_output()函数,我们可以将输出存储在变量中。

1import subprocess
2
3cmd = "date"
4
5# returns output as byte string
6returned_output = subprocess.check_output(cmd)
7
8# using decode() function to convert byte string to string
9print('Current date is:', returned_output.decode("utf-8"))

它将产生如下类型的产量

1Current date is: Thu Oct 5 16:31:41 IST 2017

因此,在上述部分中,我们讨论了关于执行 python 系统命令的基本想法,但学习没有限制. 如果您愿意,您可以从 官方文档中使用子过程模块了解更多关于 Python 系统命令的信息。

Published At
Categories with 技术
Tagged with
comments powered by Disqus