Python Execute Unix / Linux Command Examples
https://www.cyberciti.biz/faq/python-execute-unix-linux-command-examples/
os.system example (deprecated)
The syntax is:
In this example, execute the date command:
Sample outputs:
Sat Nov 10 00:49:23 IST 2012 0
In this example, execute the date command using os.popen() and store its output to the variable called now:
Sample outputs:
Today is Sat Nov 10 00:49:23 IST 2012
Say hello to subprocess
The os.system has many problems and subprocess is a much better way to executing unix command. The syntax is:
In this example, execute the date command:
Sample outputs:
Sat Nov 10 00:59:42 IST 2012 0
You can pass the argument using the following syntax i.e run ls -l /etc/resolv.confcommand:
Sample outputs:
<-rw-r--r-- 1 root root 157 Nov 7 15:06 /etc/resolv.conf 0
To store output to the output variable, run:
Sample outputs:
Today is Sat Nov 10 01:27:52 IST 2012
Another example (passing command line args):
Sample outputs:
*** Running ls -l command *** -rw-r--r-- 1 root root 157 Nov 7 15:06 /etc/resolv.conf
In this example, run ping command and display back its output:
The only problem with above code is that output, err = p.communicate() will block next statement till ping is completed i.e. you will not get real time output from the ping command. So you can use the following code to get real time output:
Sample outputs:
No hay comentarios:
Publicar un comentario