您在這裡

Command line arguments

24 二月, 2015 - 15:07

In earlier chapters, we had a number of programs that prompted for a file name using raw_input and then read data from the file and processed the data as follows:

name = raw_input('Enter file:')
handle = open(name, 'r')
text = handle.read()
...

We can simplify this program a bit by taking the file name from the command line when we start Python. Up to now, we simply run our Python programs and respond to the prompts as as follows:

python words.py
Enter file: mbox-short.txt
...

We can place additional strings after the Python file and access those commandline arguments in our Python program. Here is a simple program that demonstrates reading arguments from the command line:

import sys
print 'Count:', len(sys.argv)
print 'Type:', type(sys.argv)
for arg in sys.argv:
    print 'Argument:', arg

The contents of sys.argv are a list of strings where the first string is the name of the Python program and the remaining strings are the arguments on the command line after the Python file.

The following shows our program reading several command line arguments from the command line:

python argtest.py hello thereCount: 3Type: <type 'list'>Argument: argtest.pyArgument: helloArgument: there

There are three arguments are passed into our program as a three-element list. The first element of the list is the file name (argtest.py) and the others are the two command line arguments after the file name.

We can rewrite our program to read the file, taking the file name from the command line argument as follows:

import sys

name = sys.argv[1]handle = open(name, 'r')text = handle.read()print name, 'is', len(text), 'bytes'

We take the second command line argument as the name of the file (skipping past the program name in the [0] entry). We open the file and read the contents as follows:

python argfile.py mbox-short.txtmbox-short.txt is 94626 bytes

Using command line arguments as input can make it easier to reuse your Python programs especially when you only need to input one or two strings.