无法使用 getopt python 处理参数
为了给我的 python 脚本提供选项,我想引入一些参数。我发现在 python 中执行此操作的更好方法是使用 getopt,但是一旦我运行我的脚本,它就不会执行任何操作。请帮我!!!。这是我的代码:
def main(argv):
try:
opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
except getopt.GetoptError:
usage()
sys.exit(2)
file = None
outfile = None
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(2)
elif opt in ('-i', '--input'):
file = arg
elif opt in ('-o', '--output'):
outfile = arg
elif opt == '-t':
maininfo(file,outfile)
else:
usage()
sys.exit(2)
if __name__ =='__main__':
main(sys.argv[1:])
In order to offer options to my python script, I want to introduce some parameters. I found that the better way to do this in python is with getopt, but once I run my script it doesn't do anything. Please help me!!!. This is my code:
def main(argv):
try:
opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
except getopt.GetoptError:
usage()
sys.exit(2)
file = None
outfile = None
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(2)
elif opt in ('-i', '--input'):
file = arg
elif opt in ('-o', '--output'):
outfile = arg
elif opt == '-t':
maininfo(file,outfile)
else:
usage()
sys.exit(2)
if __name__ =='__main__':
main(sys.argv[1:])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议添加更多日志记录。这不仅可以帮助您现在,还可以帮助将来使用您的脚本的任何人。
我还将对
maininfo()
的调用移出了循环,因为您可以在文件名之前提供-t
!I suggest adding more logging. Not only will this help you out now, it'll help out whoever uses your script in future.
I also moved the call to
maininfo()
out of the loop as you could supply-t
before the filenames!您可以使用 optparse(旧版本,在 python 2.7 后将被弃用)或 argparse (新版本),这是标准的 python 模块解析参数。
希望它首先对此有所帮助
You can use optparse(old version, will be deprecated after python 2.7) or argparse ( a new version), which are standard python module parsing arguments.
Hope it helps this first
请参阅此答案: https://stackoverflow.com/a/1540399/2542738
基本上,您需要删除
'python'
来自opts
,因为它是列表opts
的第一个元素:opts.pop(0)
然后你应该没问题了。Please see this answer: https://stackoverflow.com/a/1540399/2542738
Basically, you need to remove
'python'
fromopts
as it is the first element of the listopts
:opts.pop(0)
and then you should be fine.