I am currently executing bash commands manually, by entering in shell in the python code.
How would one do this in the pythonic way?
i am currently using os.system
function to execute commands like;
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')
import subprocess process = subprocess. Popen(["ls", "-la"]) print("Completed!") Run the above code and observe the output. You will see that the message Completed! is printed before the execution of the command.
The -s option to sh (and to bash ) tells the shell to execute the shell script arriving over the standard input stream. The script then starts python - , which tells Python to run whatever comes in over the standard input stream.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
Running a Command with subprocess In the first line, we import the subprocess module, which is part of the Python standard library. We then use the subprocess. run() function to execute the command.
Possible duplicate of this question.
It is recommended to use subprocess
module instead. os.system
has been depreciated in favour of subprocess
. For more information see subprocess documentation.
import subprocess
command = 'sudo add-apt-repository ppa:ondrej/php'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With