我试图使用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)
然后在个人资料里我有这个:
^{pr2}$运行dftba SomeURL
会将一个简短的URL返回给我,但是没有任何选项工作。什么时候{{cd2>在使用之前,{cd2>不使用^}。-c
和{
我对这件事感同身受,所以如果我犯了明显的错误,我很抱歉。我觉得问题出在我的bash脚本中,只是不知道在哪里。在
任何帮助都将不胜感激。谢谢您。在
我们只关注解析器的工作
LongURL
是始终必需的位置参数。如果丢失,则会收到“参数太少”错误消息。在source
是可选的,但提供时必须包含参数。如果没有给出args.source is None
。如前所述,除了LongURL
参数之外,还必须给出source
参数。在args.copy
和args.quiet
都是布尔值;默认值是False
;如果给定,True
。(不需要default=False
参数。)我没有尝试过使用
copy
和quiet
来处理逻辑。如果LongURL
和source
之前出现问题,那么这将不会起作用。在比较这些样品:
^{pr2}$查看
parse_args
正在解析什么:sys.argv[1:]
(如果您对从.profile中获得的内容有疑问的话)。在相关问题 更多 >
编程相关推荐