Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Bash commands Python way [duplicate]

Tags:

python

bash

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')
like image 277
Sophie Rhodes Avatar asked Jan 02 '18 18:01

Sophie Rhodes


People also ask

How do I run a bash command in Python?

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.

Which commands will execute a Python script called script in bash?

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.

How do you execute a command in Python?

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!

How do you run a command in subprocess in Python?

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.


1 Answers

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()
like image 87
Michael Avatar answered Oct 24 '22 02:10

Michael