执行 Bash 命令的 Python 方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48066114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:42:43  来源:igfitidea点击:

Execute Bash commands Python way

pythonbash

提问by Sophie Rhodes

I am currently executing bash commands manually, by entering in shell in the python code.

我目前正在手动执行 bash 命令,方法是在 python 代码中输入 shell。

How would one do this in the pythonic way?

如何以 Pythonic 的方式做到这一点?

i am currently using os.systemfunction to execute commands like;

我目前正在使用os.system函数来执行命令,例如;

os.system('sudo add-apt-repository ppa:ondrej/php')
os.system('sudo apt-get update')
os.system('sudo apt-get install php7.0 php5.6 php5.6-mysql php-gettext php5.6-mbstring php-mbstring php7.0-mbstring php-xdebug libapache2-mod-php5.6 libapache2-mod-php7.0')
os.system('sudo a2dismod php7.0 ; sudo a2enmod php5.6 ; sudo service apache2 restart')

回答by Michael

Possible duplicate of this question.

这个问题的可能重复。

It is recommended to use subprocessmodule instead. os.systemhas been depreciated in favour of subprocess. For more information see subprocessdocumentation.

建议改用subprocess模块。os.system已经贬值了subprocess。有关更多信息,请参阅子流程文档。

import subprocess

command = 'sudo add-apt-repository ppa:ondrej/php'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()