Changes

Jump to: navigation, search

OPS435 Python Lab 2

248 bytes added, 14:13, 23 September 2018
PART 2 - Arguments
:#Use a temporary file for testing your work for this section.
:#In order to read arguments in Python, we will need to '''import special variablesobjects''' 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 and objects to our program.<br><br>:#Start with the following line to import special variablesobjects:<source>
import sys
</source>
print(sys.platform) # tells us our operating system platform
print(sys.argv) # tells us our arguments or shell version if issued from shell
print(len(sys.argv)) # tells us the number of command line arguments the user provide 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 list object to store data as a result of running the Python script with arguments. The '''sys.argv''' functionlist object, when used within your Python script can store the following:<ul><li>'''sys.argv''' - stores all argument dataitems</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><li>'''len(sys.argv)''' - gives the number of arguments</li></ul><br>
:#Create a new script called '''~/ops435/lab2/showargs.py''' and add the following content:<source lang="python">
#!/usr/bin/env python3
print('Print out ALL script arguments: ', arguments)
print('Print out the script name: ' + name)
print('Print out the number of argument: ', len(sys.argv))
</source>
./showargs.py
./showargs.py testing different arguments
./showargs.py argument1 argument2 argument3argument4
</source>
1,760
edits

Navigation menu