使用argparse和.profile的自定义终端命令

时间:2014-02-28 19:59:09

标签: python bash command-line argparse url-shortener

我正在尝试使用python的argparse和.profile中的函数为dft.ba URL shortener创建命令行界面,该函数调用我的python脚本。这是我的python脚本中代码的业务端:

parser = argparse.ArgumentParser(description='Shortens URLs with dft.ba')
parser.add_argument('LongURL',help='Custom string at the end of the shortened URL')
parser.add_argument('--source','-s',help='Custom string at the end of the shortened URL')
parser.add_argument('-c','--copy', action="store_true", default=False, help='Copy the shortened URL to the clipboard')
parser.add_argument('-q','--quiet', action="store_true", default=False, help="Execute without printing")
args = parser.parse_args()
target_url=args.LongURL
source=args.source
print source


query_params={'auth':'ip','target':target_url,'format':'json','src':source}
shorten='http://dft.ba/api/shorten'
response=requests.get(shorten,params=query_params)
data=json.loads(response.content)
shortened_url=data['response']['URL']
print data
print args.quiet
print args.copy

if data['error']:
    print 'Error:',data['errorinfo']['extended']
elif not args.copy:
    if args.quiet:
        print "Error: Can't execute quietly without copy flag"
    print 'Link:',shortened_url
else:
    if not args.quiet:
        print 'Link:',shortened_url
        print 'Link copied to clipboard'
    setClipboardData(shortened_url)

然后在.profile我有这个:

dftba(){
    cd ~/documents/scripts
    python dftba.py "$1" 
}

正在运行dftba SomeURL会向我发回一个缩短的网址,但没有一个选项有效。当我尝试在LongURL之前使用-s SomeSource时,它会提供error: argument --source/-s: expected one argument,之后会用到它什么都不做,省略时给出error: too few arguments。由于某种原因,-c-qerror: too few arguments。但是,如果我强制复制,我正在使用的复制到剪贴板功能完全正常。

我非常感觉到这一点,所以如果我犯了一些明显的错误,我很抱歉。我觉得我的bash脚本中有问题,我只是不知道在哪里。

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

让我们只关注解析器的作用

parser = argparse.ArgumentParser(description='Shortens URLs with dft.ba')
parser.add_argument('LongURL',help='Custom string at the end of the shortened URL')
parser.add_argument('--source','-s',help='Custom string at the end of the shortened URL')
parser.add_argument('-c','--copy', action="store_true", default=False, help='Copy the shortened URL to the clipboard')
parser.add_argument('-q','--quiet', action="store_true", default=False, help="Execute without printing")
args = parser.parse_args()
print args  # add to debug the `argparse` behavior

LongURL是一个始终需要的位置参数。如果遗失,您将收到“参数太少”错误消息。

source是可选的,但提供时必须包含参数。如果没有给出args.source is None。如上所述,source参数必须在ADDITION中给予LongURL一个。

args.copyargs.quiet都是布尔值;默认值为False;如果给出,True。 (不需要default=False参数。)

我没有尝试使用copyquiet来处理逻辑。如果LongURLsource之前出现问题,那么这不会发挥作用。

比较这些样本:

In [38]: parser.parse_args('one'.split())
Out[38]: Namespace(LongURL='one', copy=False, quiet=False, source=None)

In [41]: parser.parse_args('-s one two -c -q'.split())
Out[41]: Namespace(LongURL='two', copy=True, quiet=True, source='one')

查看parse_args正在解析的内容也可能有所帮助:sys.argv[1:](如果您对从.profile获得的内容有疑问)。