使用argparse和.profile自定义终端命令
我正在尝试为dft.ba网址缩短器创建一个命令行界面,使用的是Python的argparse库,还有一个在.profile文件中的函数来调用我的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
时,它会返回一个缩短的网址,但其他选项都不工作。当我尝试在长网址前使用-s SomeSource
时,它给我报错error: argument --source/-s: expected one argument
,如果在后面使用则没有任何反应,而省略这个选项又会提示error: too few arguments
。另外,-c
和-q
也因为某种原因提示error: too few arguments
。不过,我用的复制到剪贴板的功能在强制复制时是完全正常的。
我现在有点摸索着前进,所以如果我犯了什么明显的错误,真的很抱歉。我感觉问题可能出在我的bash脚本里,但我不知道具体在哪里。
任何帮助都将非常感激。谢谢。
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
就会是 None。也就是说,source
这个参数必须和 LongURL
一起提供。
args.copy
和 args.quiet
都是布尔值;默认值是 False
,如果给了它们就变成 True
。(其实 default=False
这个参数可以省略。)
我还没有尝试过用 copy
和 quiet
的逻辑来分析。如果在 LongURL
和 source
上出现问题,这两个参数就不会起作用。
来看看这些示例:
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')
如果你对从 .profile 获取的内容有疑问,查看 parse_args
正在解析的内容可能会有帮助:sys.argv[1:]
。