Python 命令参数

2023-09-28Python开发问题
4

本文介绍了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 命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11