Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 3

361 bytes added, 19:19, 2 June 2017
PART 2 - Running System Commands with Subprocess
:#Issue the following in ipython:<source>
system(ipconfig)
</source>You should notice an error message: ''''ipconfig command not found''''. That error occurs since that is an MS Windows command, and our current platform is Linux.<br><br>It is not usually a good idea to run system commands in Python, this makes your Python code less portable and makes it require a specific operating system or a system that has those commands available. Also, allowing python to execute commands on the operating system can be a '''security problem'''. For these reasons you should only use '''sub-process''' and '''system commands''' as a last resort and stick to Python code only.<br><br>As you may recall from lab2, you issued '''import sys''' to import special variables from the system. You can import a subprocess in order to run common non OS specific commands securely.<br><br>:#Issue the following in ipython:<source>
import subprocess
</source>
:#To view the available non OS specific commands, issue the following:<source>
dir(subprocess)
</source>:#There are many available modules and attributes available as part of subprocess, we are interested in "'''Popen'''". This method subprocess.Popen() can be used to run system commands as a child process to the Python script. This below output will create a new child process, in Python we can control this through the new Python object we just created, "'''p'''". "'''p'''" now has a collection of methods(functions that are apart of a object) available, view them with '''dir()'''.:#To demonstrate, issue the following:<source>
p = subprocess.Popen(['date'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
dir(p)
13,420
edits