Changes

Jump to: navigation, search

OPS435 Python Lab 3

68 bytes added, 12:20, 14 August 2017
PART 2 - Running System Commands with Subprocess
ipython3
</source> You can issue operating system commands by using the '''system()''' function.<br><br>
:#Issue the following in ipython:<sourcelang="python">
system(ls)
system(whoami)
system(ifconfig)
</source> You should notice the output from the Linux commands that you called is not printed to the console automatically, it's printed by ipython only. Make sure you understand the difference.<br><br>
:#Issue the following in ipython:<sourcelang="python">
system(ipconfig)
</source>You should notice an error message: ''''ipconfig command not found''''. That error occurs since that command was an MS Windows command, and our current platform is Linux.<br><br>It is not always 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:<sourcelang="python">
import subprocess
</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()'''.<br><br>
:#To demonstrate, issue the following:<sourcelang="python">
p = subprocess.Popen(['date'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
dir(p)
'9.6G'
</source>
:::3. Exit the ipython3 shell, download the checking script and check your work. Enter the following commands from the bash shell.<sourcelang="bash">
cd ~/ops435/lab3/
pwd #confirm that you are in the right directory

Navigation menu