Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.system without the output

I'm running this:

os.system("/etc/init.d/apache2 restart") 

It restarts the webserver, as it should, and like it would if I had run the command directly from the terminal, it outputs this:

* Restarting web server apache2 ... waiting [ OK ]

However, I don't want it to actually output it in my app. How can I disable it? Thanks!

like image 263
user697108 Avatar asked Apr 08 '11 14:04

user697108


People also ask

Does OS system return anything Python?

Does OS system return anything? os. system() is the state code that is returned after the execution result is executed in the Shell, with 0 indicating a successful execution.

Is OS system deprecated?

os. system function has been deprecated. In other words, this function has been replaced. The subprocess module serves as a replacement to this and Python officially recommends using subprocess for shell commands.


1 Answers

Avoid os.system() by all means, and use subprocess instead:

with open(os.devnull, 'wb') as devnull:     subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT) 

This is the subprocess equivalent of the /etc/init.d/apache2 restart &> /dev/null.

There is subprocess.DEVNULL on Python 3.3+:

#!/usr/bin/env python3 from subprocess import DEVNULL, STDOUT, check_call  check_call(['/etc/init.d/apache2', 'restart'], stdout=DEVNULL, stderr=STDOUT) 
like image 94
lunaryorn Avatar answered Oct 09 '22 11:10

lunaryorn