Python-Ref > User interaction > User input > Passing arguments to programs
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

Passing arguments to programs

For small python scripts, usually the most widely used method used for user input is via arguments given to the program on the command line on start.
The simpliest way to use command-line arguments is via the sys.argv list that contains the whole content of the command line.
Expand/Shrink
Argumenty příkazové řádky:
python userinp1.1.py file1 file2 file3
Zdroj: (userinp1.1.py)
  1   import sys
  2   
  3   print sys.argv
  4   print sys.argv[0]
  5   print sys.argv[1:]
stdout:
['userinp1.1.py', 'file1', 'file2', 'file3']
userinp1.1.py
['file1', 'file2', 'file3']
Doba běhu: 21.4 ms
The command-line arguments are most usually names of files, but it can also be any other text input.
Expand/Shrink
This is an example text in an example file.
It even has
several
lines.
Argumenty příkazové řádky:
python userinp1.2.py example.txt
Zdroj: (userinp1.2.py)
  1   import sys
  2   
  3   if len( sys.argv) <= 1:   # check if an argument was given
  4       print "give me a filename"   # if not, print an error message
  5   else:
  6       filename = sys.argv[1]
  7       f = file( filename, 'r')
  8       print f.read()
  9       f.close()
stdout:
This is an example text in an example file.
It even has
several
lines.

Doba běhu: 21.1 ms
Expand/Shrink
Zdroj: (userinp1.2.py)
  1   import sys
  2   
  3   if len( sys.argv) <= 1:   # check if an argument was given
  4       print "give me a filename"   # if not, print an error message
  5   else:
  6       filename = sys.argv[1]
  7       f = file( filename, 'r')
  8       print f.read()
  9       f.close()
stdout:
give me a filename
Doba běhu: 28.4 ms