I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print ('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
Just adding to Frederic's answer, for example if you call your script as follows:
./myscript.py foo bar
sys.argv[0]
would be "./myscript.py"sys.argv[1]
would be "foo" andsys.argv[2]
would be "bar" ... and so forth.In your example code, if you call the script as follows
./myscript.py foo
, the script's output will be "Hello there foo".sys.argv[1] contains the first command line argument passed to your script.
For example, if your script is named
hello.py
and you issue:or:
Your script will print: