Python 命令参数

2022-01-21 00:00:00 python parsing arguments args

问题描述

我已经在谷歌上搜索了将近一个小时,但被卡住了.

I have been googling almost an hour and am just stuck.

对于一个脚本,stupidadder.py,它将 2 添加到命令 arg.

for a script, stupidadder.py, that adds 2 to the command arg.

例如python 愚蠢的adder.py 4

e.g. python stupidadder.py 4

打印 6

python愚蠢的adder.py 12

python stupidadder.py 12

打印 14

到目前为止我已经用谷歌搜索过:

I have googled so far:

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('x', metavar='x', type=int, nargs='+',
                    help='input number')

...

args = parser.parse_args()
print args
x = args['x']  # fails here, not sure what to put
print x + 2

我在任何地方都找不到直接的答案.文档太混乱了.:( 有人可以帮忙吗?请,谢谢.:)

I can't find a straightforward answer to this anywhere. the documentation is so confusing. :( Can someone help? Please and thank you. :)


解决方案

我不完全确定你的目标是什么.但如果这就是你所要做的一切,你不必变得非常复杂:

I'm not entirely sure what your goal is. But if that's literally all you have to do, you don't have to get very complicated:

import sys
print int(sys.argv[1]) + 2

这里是一样的,但有一些更好的错误检查:

Here is the same but with some nicer error checking:

import sys

if len(sys.argv) < 2:
    print "Usage: %s <integer>" % sys.argv[0]
    sys.exit(1)

try:
    x = int(sys.argv[1])
except ValueError:
    print "Usage: %s <integer>" % sys.argv[0]
    sys.exit(1)

print x + 2

示例用法:

C:Usersuser>python blah.py
Usage: blah.py <integer>

C:Usersuser>python blah.py ffx
Usage: blah.py <integer>

C:Usersuser>python blah.py 17
19

相关文章