subprocess module allows you to start new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions like os.system, os.spawn, os.popen.
With subprocess module, one can execute system commands , capture the output and redirect the output.
#Using ls utility > subprocess.check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' #To run above command on shell : > subprocess.check_output("ls -l /dev/null",shell=True) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
check_output(*popenargs, **kwargs) – Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError.
To start the new process, subprocess module has method called popen.
import subprocess process = subprocess.Popen(['ls', '-l', '/dev/null'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() print stdout #output crw-rw-rw- 1 root root 1, 3 Nov 1 08:15 /dev/null
Other useful subprocess methods & terms :
>>> dir(subprocess) ['CREATE_NEW_CONSOLE', 'CREATE_NEW_PROCESS_GROUP', 'CalledProcessError', 'MAXFD', 'PIPE', 'Popen', 'STARTF_USESHOWWINDOW', 'STARTF_USESTDHANDLES', 'STARTUPINFO', 'STDOUT', 'STD_ERROR_HANDLE', 'STD_INPUT_HANDLE', 'STD_OUTPUT_HANDLE', 'SW_HIDE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_active', '_args_from_interpreter_flags', '_cleanup', '_demo_posix', '_demo_windows', '_eintr_retry_call', '_subprocess', 'call', 'check_call', 'check_output', 'errno', 'gc', 'list2cmdline', 'msvcrt', 'mswindows', 'os', 'pywintypes', 'signal', 'sys', 'threading', 'traceback', 'types']
platform module in Python is used to access the underlying platform’s data,
such as, hardware, operating system, and interpreter version information. Some useful methods are listed below :
import platform >>> platform.system() 'Windows' >>> platform.processor() 'Intel64 Family 6 Model 58 Stepping 9, GenuineIntel' >>> platform.machine() 'AMD64' >>> platform.architecture() ('32bit', 'WindowsPE') >>> platform.win32_ver() ('8', '6.2.9200', 'SP0', u'Multiprocessor Free') >>> platform.uname() ('Windows', 'user', '8', '6.2.9200', 'AMD64', 'Intel64 Family 6 Model 58 Stepping 9, GenuineIntel') >>> platform.version() '6.2.9200' >>> platform.python_build() ('v2.7.13:a06454b1afa1', 'Dec 17 2016 20:42:59') >>> platform.python_compiler() 'MSC v.1500 32 bit (Intel)' >>> platform.python_version() '2.7.13' >>> platform.python_implementation() 'CPython' >>> platform.linux_distribution() ('Ubuntu', '14.04', 'trusty') >>> platform.version() '6.2.9200'
Example with code snippet is given below to explain, how platform & subprocess modules can be combined and used. Following script runs on both, Linux & Windows Environment . Script displays all current TCP/IP network configuration values.
#!/usr/bin/python import subprocess import platform def call_windows(): print "Hello Windows" output = subprocess.check_output("ipconfig",shell=True) print output def call_linux(): print "Hello Linux" output = subprocess.check_output("ifconfig",shell=True) print output if platform.system() == 'Windows': call_windows() elif platform.system() == 'Linux': call_linux() else: pass
Output on Windows System :
Hello Windows Windows IP Configuration Wireless LAN adapter Lenovo Easyplus Hotspot : Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Wireless LAN adapter Wi-Fi: Connection-specific DNS Suffix . : domain.name Link-local IPv6 Address . . . . . : fe80::9145:2c6:57de:7f97%15 IPv4 Address. . . . . . . . . . . : 192.168.126.15 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : fe80::217:7cff:fe70:4a9a%15 192.168.126.1 Ethernet adapter Ethernet: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Tunnel adapter isatap.domain.name: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : domain.name Tunnel adapter Local Area Connection* 13: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Tunnel adapter Teredo Tunneling Pseudo-Interface: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . :
Output on Linux System :
Hello Linux lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) venet0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:127.0.0.2 P-t-P:127.0.0.2 Bcast:0.0.0.0 Mask:255.255.255.255 UP BROADCAST POINTOPOINT RUNNING NOARP MTU:1500 Metric:1 RX packets:2624 errors:0 dropped:0 overruns:0 frame:0 TX packets:1803 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:218487 (218.4 KB) TX bytes:161904 (161.9 KB) venet0:0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:172.35.16.221 P-t-P:172.35.16.221 Bcast:172.35.16.221 Mask:255.255.255.255 UP BROADCAST POINTOPOINT RUNNING NOARP MTU:1500 Metric:1
I hope this example will be useful to understand platform & subprocess module in python. To learn more about platform & subprocess, please refer following links :
https://docs.python.org/2/library/subprocess.html
https://docs.python.org/2/library/platform.html