Python 命令参数 [英] Python Command Args

查看:32
本文介绍了Python 命令参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于Python 命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆