Python Command Args(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 命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 命令参数


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01