在Python中使用“from”作为脚本参数

2024-05-20 01:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的赋值要求“from”用作命令行输入的参数。你知道吗

p = optparse.OptionParser()
p.add_option("--from")
p.add_option("--to")
p.add_option("--file", default="carla_coder.ics")
options, arguments = p.parse_args()

print options.from

显然,“from”是一个Python关键字。。。有什么办法可以解决这个问题吗?基本上,脚本应该使用 file.py --from=dd/mm/yyyy --to=dd/mm/yyyy --file=file


Tags: to命令行fromadddefault参数ddfile
2条回答

使用Python的getattr函数:

getattr(options, 'from')

其行为类似于options.from,只是属性名不必遵循Python通常的变量命名规则(包括关键字冲突)。你知道吗

使用the ^{} attribute指定名称:

p.add_option(" from", dest="foo")

print options.foo

相关问题 更多 >