Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Command-Line Arguments

Python3 Command-Line Arguments

Python3 Basic Syntax Python3 Basic Syntax

Python provides the getopt module to get command-line arguments.


$ python test.py arg1 arg2 arg3

In Python you can also use sys 's sys.argv to get command-line arguments:

**Note:** sys.argv[0] is the script name.

Example

The test.py file code is as follows:

Example

#!/usr/bin/python3

import

sys

print

(

'Number of arguments:'

,

len

(

sys

.

argv

)

,

' arguments.'

)

print

(

'Argument list:'

,

str

(

sys

.

argv

)

)

print

(

'Script name:'

,

str

(

sys

.

argv

[

0

]

)

)

The output of the code above is:


$ python3 test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
脚本名: test.py

The getopt module

The getopt module is dedicated to handling command-line arguments; it obtains command-line options and arguments, i.e. sys.argv. Command-line options make a program's parameters more flexible. It supports short option mode - and long option mode --.

This module provides two methods and one exception for parsing command-line arguments.

The getopt.getopt method

The getopt.getopt method parses a list of command-line arguments with the following syntax:


getopt.getopt(args, options[, long_options])

Method parameter description:

The method returns two elements: the first is a (option, value) list of tuples. The second is the argument list, containing those arguments without - or --.

Next we define a site() function, then enter the site name name and URL urlfrom the command line; the abbreviations n and u:

Example

import

sys

import

getopt

 

 

def

site

(

)

:

    name

=

None

    url

=

None

 

    argv

=

sys

.

argv

[

1

:

]

 

   

try

:

        opts

,

args

=

getopt

.

getopt

(

argv

,

"n:u:"

)

 

Short option mode

     

   

except

:

       

print

(

"Error"

)

 

   

for

opt

,

arg

in

opts:

       

if

opt

in

[

'-n'

]

:

            name

=

arg

       

elif

opt

in

[

'-u'

]

:

            url

=

arg

     

 

   

print

(

name +

" "

)

 

site

(

)

To test the code above, enter the following on the command line:

python3 test.py -n RUNOOB -u www.runoob.com

The output is:

RUNOOB www.runoob.com

The following example demonstrates the long option mode:

Example

import

sys

import

getopt

 

def

site

(

)

:

    name

=

None

    url

=

None

 

    argv

=

sys

.

argv

[

1

:

]

 

   

try

:

        opts

,

args

=

getopt

.

getopt

(

argv

,

"n:u:"

,

 

                                   

[

"name="

,

                                   

"url="

]

)

 

Long option mode

     

   

except

:

       

print

(

"Error"

)

 

   

for

opt

,

arg

in

opts:

       

if

opt

in

[

'-n'

,

'--name'

]

:

            name

=

arg

       

elif

opt

in

[

'-u'

,

'--url'

]

:

            url

=

arg

     

 

   

print

(

name +

" "

)

 

site

(

)

To test the code above, enter the following on the command line:

python3 test.py -n RUNOOB -u www.runoob.com

The output is:

RUNOOB www.runoob.com

Another method is getopt.gnu_getopt, which is used less often and is not covered here.


Exception getopt.GetoptError

This exception is raised when the argument list is not found, or when a required argument for an option is empty.

The exception's argument is a string describing the cause of the error. The attribute msg and opt holds the error message for the related option.

Example

Suppose we create a script that receives two file names from the command line, along with another option for viewing the script's usage. The script is used as follows:


usage: test.py -i  -o 

The test.py file code is as follows:

Example

#!/usr/bin/python3

import

sys

,

getopt

def

main

(

argv

)

:

   inputfile

=

''

   outputfile

=

''

   

try

:

      opts

,

args

=

getopt

.

getopt

(

argv

,

"hi:o:"

,

[

"ifile="

,

"ofile="

]

)

   

except

getopt

.

GetoptError

:

     

print

(

'test.py -i -o '

)

     

sys

.

exit

(

2

)

   

for

opt

,

arg

in

opts:

     

if

opt

==

'-h'

:

         

print

(

'test.py -i -o '

)

         

sys

.

exit

(

)

     

elif

opt

in

(

"-i"

,

"--ifile"

)

:

         inputfile

=

arg

     

elif

opt

in

(

"-o"

,

"--ofile"

)

:

         outputfile

=

arg

   

print

(

'The input file is:'

,

inputfile

)

   

print

(

'The output file is:'

,

outputfile

)

if

name

==

"main"

:

   main

(

sys

.

argv

[

1

:

]

)

The output of the code above is:


$ python3 test.py -h
usage: test.py -i  -o 

$ python3 test.py -i inputfile -o outputfile
输入的文件为: inputfile
输出的文件为: outputfile

Python3 Basic Syntax Python3 Basic Syntax