Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

How can I launch a bash command with multiple args (for example "sudo apt update") from a python script?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

@milne's answer works, but subprocess.call() gives you little feedback.

I prefer to use subprocess.check_output() so you can analyse what was printed to stdout:

 import subprocess
 res = subprocess.check_output(["sudo", "apt", "update'])
 for line in res.splitlines():
     # process the output line by line

check_output throws an error on on-zero exit of the invoked command

Please note that this doesn't invoke bash or another shell if you don't specify the shell keyword argument to the function (the same is true for subprocess.call(), and you shouldn't if not necessary as it imposes a security hazard), it directly invokes the command.

If you find yourself doing a lot of (different) command invocations from Python, you might want to look at plumbum. With that you can do the (IMO) more readable:

from plumbum.cmd import sudo, apt

res = sudo[apt["update"]]()
share|improve this answer

It is possible you use the bash as a program, with the parameter -c for execute the commands:

Example:

bashCommand = "sudo apt update"
output = subprocess.check_output(['bash','-c', bashCommand])
share|improve this answer

The subprocess module is designed to do this:

import subprocess
subprocess.call(["sudo", "apt", "update"])

If you would like the script to terminate if the command fails, you might consider using check_call() instead of parsing the return code yourself:

subprocess.check_call(["sudo", "apt", "update"])
share|improve this answer
    
this gave me the following traceback : Traceback (most recent call last): File "/home/Dremor/test.py", line 3, in <module> subprocess.call('sudo', 'yum', 'update') File "/usr/lib64/python3.4/subprocess.py", line 537, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib64/python3.4/subprocess.py", line 767, in __init__ raise TypeError("bufsize must be an integer") TypeError: bufsize must be an integer (I'm using yum as I'm using Fedora as main OS) –  Dremor Mar 16 at 16:07
2  
You forgot the square brackets –  Miline Mar 16 at 16:19
1  
Also note that subprocess.call() is blocking while subprocess.Popen() is non-blocking.. –  heemayl Mar 16 at 18:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.