python - 获取原始输入作为选项?

标签 python getopt

总的来说,我对 python 还比较陌生,主要是用它来轻松地移动文件,而我最近一直在做的是使用 raw_input 来获取一个名称以作为目录名称变量传递。但是我说 getopt 并认为尝试获取 raw_input 提示用户作为选项的变量会节省时间和精力。但是我找不到任何我想做的事情的例子。

无需等待它提示我,我只需键入 meego.py shortname=example 并让它执行即可。这件事做起来容易吗?

这是我基本没有的

var = raw_input("Shortname=")

print 'starting: ' + str(var)

svn_app = svn_root + "/" + var    


shutil.copyfile(riproot + '/images/ApplicationIcon.png',
            svn_app + '/images/ApplicationIcon.png') 

print 'done: ' + str(var)

最佳答案

如果您的 Python >= 2.7,请使用 argparse模块(它是标准库的一部分)。

如果你有 2.3 <= Python < 2.7 install the argparse module .

由于 Python 的 future 正朝着或已经在使用 argparse 模块,因此您应该使用它来代替旧模块之一(如 optparse 或 getopt)。


import argparse

parser=argparse.ArgumentParser()
parser.add_argument('--shortname')
args=parser.parse_args()

print 'starting: ' + str(args.shortname)

可以这样使用:

% prog.py --shortname example
starting: example

关于python - 获取原始输入作为选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425602/

相关文章:

python - 使用 Python 和 Raspberry Pi 快速捕获和将 2D 图像堆叠为 3D numpy 数组

python - 仅使用 python 加载捆绑的 python 框架依赖项

c - getopt 不解析参数的可选参数

c++ - getopt 无法检测到选项的缺失参数

Bash getopts : recognizing negative options (-x- or +x)?

bash - 如何将长选项传递给 bash 脚本?

python - 为 Python LocustIO 格式化 Json

python - pandas 按列分组,然后从每个组的日期列中获取平均天数

c - 使用 getopt_long 检测没有参数

python - 使用 python 更改文件权限的 Chmod 问题