执行Bash命令Python方式[重复]

问题描述 投票:6回答:1

这个问题在这里已有答案:

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

如何用pythonic方式做到这一点?

我目前正在使用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')
python bash python-3.x python-2.7
1个回答
7
投票

this question可能重复。

建议使用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()
© www.soinside.com 2019 - 2024. All rights reserved.