【发布时间】:2014-04-02 00:27:39
【问题描述】:
我正在尝试使用 python 的 argparse 和 .profile 中调用我的 python 脚本的函数为dft.ba URL shortener 创建一个命令行界面。这是我的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 将向我吐出一个缩短的 URL,但没有一个选项起作用。当我尝试在 LongURL 之前使用-s SomeSource 时,它会给出error: argument --source/-s: expected one argument,之后使用它什么也不做,当被省略时给error: too few arguments。 -c 和 -q 出于某种原因给 error: too few arguments。但是,如果我强制复制,我正在使用的复制到剪贴板功能可以正常工作。
我非常想通过这件事,所以如果我犯了一些明显的错误,我很抱歉。我感觉问题出在我的 bash 脚本中,我只是不知道在哪里。
任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: python bash command-line argparse url-shortener