15

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

15

@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, echo, cut

res = sudo[apt["update"]]()
chain = echo["hello"] | cut["-c", "2-"]
chain()
  • Is it recommended to use (os.popen or os.system), ex: res = os.popen('sudo apt update').read()? @Anthon – alper Aug 8 '18 at 13:48
  • 1
    @alper Read 0324 python.org/dev/peps/pep-0324. That explains the rationale for making subprocess although os.system and os.popen already existed. Such PEPs are non-trivial to get accepted. Several people have given much more thought to that than you or I ever will. And subprocess has improved since 2003, the others are just still there for backward compatibility. Have you red the os.system manual page: The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. – Anthon Aug 8 '18 at 18:58
  • 1
    @alper Yes you could. As I indicated that is a potential security hazard, so I don't know why you think that is recommended. And invoking sudo is only going to make that more severe. Maybe using python-apt is a better solution (I have not looked into that myself). – Anthon Aug 31 '18 at 13:36
  • 1
    @alper in that case take a serious look at plumbum, it is worth getting up to speed with that. – Anthon Aug 31 '18 at 13:50
  • 1
    @alper If you are on Python3 you need to do that, on Python2 you don't. Please don't use the commenting here as a chat system. If you have a question post it as such. – Anthon Sep 2 '18 at 17:07
8

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])
6

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"])
  • 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 '15 at 16:07
  • 3
    You forgot the square brackets – Milind Dumbare Mar 16 '15 at 16:19
  • 1
    Also note that subprocess.call() is blocking while subprocess.Popen() is non-blocking.. – heemayl Mar 16 '15 at 18:02
  • What do you mean by "blocking"? @heemayl – alper Sep 2 '18 at 17:19
2

Also you can use 'os.popen'.

Example:

import os

command = os.popen('ls -al')
print(command.read())
print(command.close())

Output:

total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root   77 ago 13 21:53 test.py

None
0

use subprocess module

import subprocess
command = 'sudo apt update'
subprocess.check_call(command.split())
  • why am i getting an error when i use it – aquagremlin Apr 1 at 19:52
  • subprocess.check_call(["sudo", "apt", "update"]) – aquagremlin Apr 1 at 19:52
  • CalledProcessError Traceback (most recent call last) <ipython-input-21-33ce645708e7> in <module>() ----> 1 subprocess.check_call(["sudo", "apt", "update"]) /usr/lib/python2.7/subprocess.pyc in check_call(*popenargs, **kwargs) 188 if cmd is None: 189 cmd = popenargs[0] --> 190 raise CalledProcessError(retcode, cmd) 191 return 0 192 CalledProcessError: Command '['sudo', 'apt', 'update']' returned non-zero exit status 1 – aquagremlin Apr 1 at 19:52
  • this error only happens when i run it in a jupyter notebook – aquagremlin Apr 1 at 19:53
  • maybe i'll start a new question since this is ot – aquagremlin Apr 1 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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