【问题标题】:Custom terminal command with argparse and .profile带有 argparse 和 .profile 的自定义终端命令
【发布时间】: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


    【解决方案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 is None。正如所写,source 参数必须在添加到LongURL 之一中给出。

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

    我还没有尝试使用copyquiet 处理逻辑。如果LongURLsource 早先出现问题,这将不会发挥作用。

    比较这些示例:

    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')
    

    查看 parse_args 正在解析的内容也可能会有所帮助:sys.argv[1:](如果您对从 .profile 获得的内容有疑问)。

    【讨论】:

    • 感谢您的回复。出于某种原因,我忽略了我实际上在-s 之后放置了一个源,所以输入是dftba -s SOURCE LongURL。它仍然给出error: argument --source/-s: expected one argument。在那种情况下,它永远不会到达print args,所以我不知道那里发生了什么。尝试-c-q 得到error: too few arguments,再次不打印args。抱歉,这不是帖子的全部内容,我写的时候脑子有点乱。
    • 检查“sys.argv”。 '"$1"' 可能会给出一个 .string。
    • 啊哈!我想可能是这个。当我运行dftba -q URL 时,sys.argv 是 [dftba.py,'-q']。当我将“$2”添加到 .profile 时,它​​会正确执行(它会出错,但它应该这样做)。环顾四周后,“$@”似乎可以满足我的需要。话虽如此,虽然-s SOURCE 不会导致错误,但它实际上并没有工作。我一定是误解了 API 的文档。谢谢您的帮助。我应该如何将其标记为已解决?
    • 像魅力一样工作。我真是个笨蛋。它确实说shorten(POST),至少我现在知道that 是什么意思。有道理它会是一个帖子,考虑一下。非常感谢帮忙。你有没有机会知道我是否/如何将它作为“可安装”的东西分发,现在我让它正常运行了?
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2020-07-23
    • 2013-08-19
    • 2020-01-14
    相关资源
    最近更新 更多