Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 3

752 bytes added, 19:01, 2 June 2017
PART 2 - Running System Commands with Subprocess
== PART 2 - Running System Commands with Subprocess ==
:The remainder of this lab will allow you to run operating system commands via your Python script. Although there are different ways in which to issue operating system commands, you will learn how to issue them within a Python script to run in a secure manner regardless of the type of operating system platform (eg Linux, Windows, MacOSX). You may have recalled using the alias command This last part of the investigation will give you access to system commands within your python scripts. While we are able to run some bash commands inside the ipython3 environment, these do not transfer over into the python code we write. 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 speicifc operating system or a system that has those commands available. There is also the case of security, allowing python to execute commands on the system can be a security problem if care isn't taken. For these reason you should only use subprocess and the system commands as a last resort and stick to Python code only.
'''Perform the Following Steps:'''
:#Start the ipython3 shell:<source>
ipython3
</source> You can issue operating system commands by using the '''system()''' function.<br><br>
:#Issue the following in ipython:<source>
system(ls)
system(whoami)
system(ifconfig)
</source> You should notice output from your Linux commands issued.<br><br>
:#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.
 
 
 
<source>
import subprocess
dir(subprocess)
13,420
edits