我想创建dft.ba URL shortener命令行界面使用python的argparse和调用我的python脚本.profile中的函数。这是代码在我的python脚本营业结束:自定义终端命令与argparse和.profile
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脚本中,我只是不知道在哪里。
任何帮助将不胜感激。谢谢。
感谢您的回复。出于某种原因,我省略了实际上在'-s'之后放置源的事实,所以输入是'dftba -s SOURCE LongURL'。它仍然给出'错误:参数--source/-s:预期的一个参数'。在那种情况下,它永远不会'打印参数',所以我不知道那里发生了什么。尝试'-c'和'-q'会给出'错误:太少的参数',再次不会打印'args'。对不起,这并不是所有的帖子,当我写这篇文章的时候,脑子有点混乱。 – Whonut
检查'sys.argv'。 ''$ 1''可能会给一个.string。 – hpaulj
啊哈!我认为这可能是这个。当我运行'dftba -q URL'时,sys.argv是[dftba.py,'-q']。当我向.profile中添加“$ 2”时,它会正确执行(它是错误,但它意味着这么做)。经过一番环视后,“$ @”似乎可以满足我的需求。这就是说,虽然'-s SOURCE'不会导致错误,它实际上并不_work_。我必须误解API的文档。谢谢您的帮助。我应该如何将此标记为已解决? – Whonut