带argparse和.profi的自定义终端命令

2024-05-29 05:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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脚本中,只是不知道在哪里。在

任何帮助都将不胜感激。谢谢您。在


Tags: the脚本addparserurlsourcedatahelp
1条回答
网友
1楼 · 发布于 2024-05-29 05:11:20

我们只关注解析器的工作

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。如前所述,除了LongURL参数之外,还必须给出source参数。在

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

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

比较这些样品:

^{pr2}$

查看parse_args正在解析什么:sys.argv[1:](如果您对从.profile中获得的内容有疑问的话)。在

相关问题 更多 >

    热门问题