1,234
edits
Changes
→PART 2 - Arguments
'''Perform the following steps:'''
:#Access Use a temporary file for testing your ipython3 shellwork for this section.:<source lang="bash">ipython3</source>#In order to read arguments in Python, we will need to '''import special variables''' from the system. This is a standard 'library' of code provided by the developers of Python. By issuing '''import sys''', you have loaded code written by another person, each 'library' that gets loaded will give us extra functionality in our program. This is done by issuing the import sys function within your ipython3 shell.<br><br>:#Issue Start with the following line to access your ipython3 shell and import special variables:<source>
import sys
</source>
:#To inspect this library, and look at all that it contains, we can use the '''dir()''' function. This can be used to inspect any library (in fact, inspect other items other than libraries) in order to refer to functions and values that are available. Issue the following function:<source>dir(sys)</source>You may feel overwhelmed with all of this information, but not to worry, there are additional tools and tips on how to obtain information regarding these functions contain in the library.<br><br>:#Issue Call the following functions and note what they do:<source lang="python">
print(sys.version) # tells us our python version
print(sys.platform) # tells us our operating system platform
print(sys.argv) # tells us our arguments or shell version if issued from shell
sys.exit() # will immediately end the running Python script, ignoring the remaining lines in the Python script
</source><br>Instead of using the '''input()''' function to prompt the user for data, we can use the '''sys.argv''' function to store data as a result of running the Python script with arguments. The '''sys.argv''' function, when used within your Python script can store the following:<ul><li>'''sys.argv''' - stores all argument data</li><li>'''sys.argv[0]''' - stores the name of the script/program</li><li>'''sys.argv[1]''' - stores the first argument</li><li>'''sys.argv[2]''' - stores the second argument</li><li>etc...</li></ul><br>
:#Create a new script called '''~/ops435/lab2/showargs.py''' and add the following content:<source lang="python">
#!/usr/bin/env python3