How to read/process command line arguments?

2018-12-31 01:20发布

17条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 02:11

There is also argparse stdlib module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

Usage:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10
查看更多
流年柔荑漫光年
3楼-- · 2018-12-31 02:13

If you need something fast and not very flexible

main.py:

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)

Then run python main.py James Smith

to produce the following output:

Hello James Smith

查看更多
不流泪的眼
4楼-- · 2018-12-31 02:15
import sys

print("\n".join(sys.argv))

sys.argv is a list that contains all the arguments passed to the script on the command line.

Basically,

import sys
print(sys.argv[1:])
查看更多
泪湿衣
5楼-- · 2018-12-31 02:17

Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.

The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.

查看更多
爱死公子算了
6楼-- · 2018-12-31 02:18

You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando

查看更多
登录 后发表回答