使用 optparse 接受参数的最 Pythonic 方式 [英] Most pythonic way of accepting arguments using optparse

查看:29
本文介绍了使用 optparse 接受参数的最 Pythonic 方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个 python 文件,它利用 sys.argv[1] 在命令行接受一个字符串.然后它对该字符串执行操作,然后将修改后的字符串返回到命令行.

I currently have a python file that utilizes sys.argv[1] to accept a string at the command line. It then performs operations on that string and then returns the modified string to the command line.

我想实现一个批处理模式选项,在该选项中我可以提供一个字符串文件(每行一个,fwiw)并将其返回到命令行,以便我可以重定向输出执行类似

I would like to implement a batch mode option in which I can provide a file of strings (one per line, fwiw) and have it return to the command line so that I can redirect the output doing something like

$ python script.py -someflag file.txt > modified.txt 

同时仍保留当前功能.

我只运行 2.6,所以 argparse 不是一个选项.我看过的教程要么使用 argparse、getopt,要么深入研究太复杂/不适用的示例.

I am only running 2.6, so argparse is not an option. The tutorials I have seen either use argparse, getopt, or delve into examples that are too complex/don't apply.

检查输入并采取适当行动的最佳方法是什么?

What is the best way to check the input and act appropriately?

推荐答案

argparse 仍然是一个选项,只是不是内置于 2.6.您仍然可以像安装任何 3rd 方软件包一样安装它(例如,使用 easy_install argparse).

argparse is still an option, it's just not built into 2.6. You can still install it like any 3rd party package (for example, using easy_install argparse).

此代码的示例是:

import sys
import argparse

p = argparse.ArgumentParser(description="script.py")
p.add_argument("-s", dest="string")
p.add_argument("-f", dest="infile")

args = p.parse_args()

if args.infile == None and args.string == None:
    print "Must be given either a string or a file"
    sys.exit(1)
if args.infile != None and args.string != None:
    print "Must be given either a string or a file, not both"
    sys.exit(1)
if args.infile:
    # process the input file one string at a time
if args.string:
    # process the single string

这篇关于使用 optparse 接受参数的最 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆