python argparse - 在没有命令行的情况下传递值 [英] python argparse - pass values WITHOUT command line

查看:71
本文介绍了python argparse - 在没有命令行的情况下传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我不了解 Python 的 argparse 的一些基本知识.

我正在尝试将 Google YouTube API 用于 python 脚本,但我不明白如何在不使用命令行的情况下将值传递给脚本.

例如,此处是 API 示例.github 和其他地方的示例将这个示例显示为从命令行调用,在调用脚本时从那里传递 argparse 值.

我不想使用命令行.我正在构建一个使用装饰器获取用户登录凭据的应用程序,当该用户想要上传到他们的 YouTube 帐户时,他们提交一个表单,然后该表单将调用此脚本并将 argparse 值传递给它.

如何将值从另一个 python 脚本传递给 argparser(请参阅下面的 YouTube 上传 API 脚本部分代码)?

如果 __name__ == '__main__':argparser.add_argument("--file", required=True, help="要上传的视频文件")argparser.add_argument("--title", help="视频标题", default="测试标题")argparser.add_argument("--description", help="视频描述",默认=测试描述")argparser.add_argument("--category", default="22",help="数字视频类别." +请参阅 https://developers.google.com/youtube/v3/docs/videoCategories/list")argparser.add_argument("--keywords", help="视频关键字,逗号分隔",默认="")argparser.add_argument("--privacyStatus", options=VALID_PRIVACY_STATUSES,default=VALID_PRIVACY_STATUSES[0], help="视频隐私状态.")args = argparser.parse_args()如果不是 os.path.exists(args.file):exit("请使用 --file= 参数指定有效文件.")youtube = get_authenticated_service(args)尝试:initialize_upload(youtube,args)除了 HttpError,e:打印 "发生 HTTP 错误 %d:\n%s" % (e.resp.status, e.content)

<小时>

根据请求,这是我使用标准方法初始化字典或使用 argparse 创建字典时得到的 400 错误的回溯.我以为我是由于参数格式错误而得到的,但也许不是:

回溯(最近一次调用最后一次):文件C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py",第 1535 行,在 __call__ 中rv = self.handle_exception(请求,响应,e)文件C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py",第 1529 行,在 __call__ 中rv = self.router.dispatch(请求,响应)文件C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py",第 1278 行,在 default_dispatcher 中返回 route.handler_adapter(请求,响应)文件C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py",第 1102 行,在 __call__ 中返回 handler.dispatch()文件C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py",第 572 行,在调度中返回 self.handle_exception(e, self.app.debug)文件C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py",第 570 行,在调度中返回方法(*args, **kwargs)setup_oauth 中的文件C:\Users\...\testapp\oauth2client\appengine.py",第 796 行响应 = 方法(request_handler,*args,**kwargs)文件C:\Users\...\testapp\testapp.py",第 116 行,在 get可恢复上传(插入请求)文件C:\Users\...\testapp\testapp.py",第 183 行,在 resumable_upload 中状态,响应 = insert_request.next_chunk()文件C:\Users\...\testapp\oauth2client\util.py",第 129 行,位于 positional_wrapper返回包装(*args,**kwargs)文件C:\Users\...\testapp\apiclient\http.py",第 874 行,在 next_chunk返回 self._process_response(resp, content)文件C:\Users\...\testapp\apiclient\http.py",第 901 行,在 _process_response引发 HttpError(resp, content, uri=self.uri)HttpError: <HttpError 400 请求 https://www.googleapis.com/upload/youtube/v3/videos?alt=json&part=status%2Csnippet&uploadType=resumable 返回错误请求">

解决方案

这是否是最好的方法真的需要你自己去弄清楚.但是在没有命令行的情况下使用 argparse 容易.我一直这样做是因为我有可以从命令行运行的批处理.或者也可以由其他代码调用 - 如上所述,这非常适合单元测试.例如,argparse 尤其擅长默认参数.

从您的样品开始.

导入 argparseargparser = argparse.ArgumentParser()argparser.add_argument("--file", required=True, help="要上传的视频文件")argparser.add_argument("--title", help="视频标题", default="测试标题")argparser.add_argument("--description", help="视频描述",默认=测试描述")argparser.add_argument("--category", default="22",help="数字视频类别." +请参阅 https://developers.google.com/youtube/v3/docs/videoCategories/list")argparser.add_argument("--keywords", help="视频关键字,逗号分隔",默认="")VALID_PRIVACY_STATUSES = ("私人","公共")argparser.add_argument("--privacyStatus", options=VALID_PRIVACY_STATUSES,default=VALID_PRIVACY_STATUSES[0], help="视频隐私状态.")#pass 在任何位置或必需的变量.. 作为列表中的字符串# 对应于 sys.argv[1:].不是字符串 =>神秘的错误.args = argparser.parse_args(["--file", "myfile.avi"])#您可以填充其他可选参数,而不仅仅是位置/必需#args = argparser.parse_args(["--file", "myfile.avi", "--title", "我的标题"])打印变量(参数)#修改你认为合适的它们,但不再进行验证#所以最好使用 parse_args.args.privacyStatus = "某些状态不在选择中 - 已解析"args.category = 42打印变量(参数)#proceed 和以前一样,系统不关心它是否来自命令行# youtube = get_authenticated_service(args)

输出:

{'category': '22', 'description': 'Test Description', 'title': 'Test Title', 'privacyStatus': 'private', 'file': 'myfile.avi', '关键字': ''}{'category': 42, 'description': 'Test Description', 'title': 'Test Title', 'privacyStatus': '某些状态不在选择中 - 已经解析', 'file': 'myfile.avi','关键字':''}

I think I'm not understanding something basic about python's argparse.

I am trying to use the Google YouTube API for python script, but I am not understanding how to pass values to the script without using the command line.

For example, here is the example for the API. The examples on github and elsewhere show this example as being called from the command line, from where the argparse values are passed when the script is called.

I don't want to use the command line. I am building an app that uses a decorator to obtain login credentials for the user, and when that user wants to upload to their YouTube account, they submit a form which will then call this script and have the argparse values passed to it.

How do I pass values to argparser (see below for portion of code in YouTube upload API script) from another python script?

if __name__ == '__main__':
    argparser.add_argument("--file", required=True, help="Video file to upload")
    argparser.add_argument("--title", help="Video title", default="Test Title")
    argparser.add_argument("--description", help="Video description",
        default="Test Description")
    argparser.add_argument("--category", default="22",
        help="Numeric video category. " +
            "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
    argparser.add_argument("--keywords", help="Video keywords, comma separated",
        default="")
    argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
        default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
    args = argparser.parse_args()

    if not os.path.exists(args.file):
        exit("Please specify a valid file using the --file= parameter.")

    youtube = get_authenticated_service(args)
    try:
        initialize_upload(youtube, args)
    except HttpError, e:
        print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)


EDIT: Per request, here is the traceback for the 400 Error I am getting using either the standard method to initialize a dictionary or using argparse to create a dictionary. I thought I was getting this due to badly formed parameters, but perhaps not:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "C:\Users\...\testapp\oauth2client\appengine.py", line 796, in setup_oauth
    resp = method(request_handler, *args, **kwargs)
  File "C:\Users\...\testapp\testapp.py", line 116, in get
    resumable_upload(insert_request)
  File "C:\Users\...\testapp\testapp.py", line 183, in resumable_upload
    status, response = insert_request.next_chunk()
  File "C:\Users\...\testapp\oauth2client\util.py", line 129, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\...\testapp\apiclient\http.py", line 874, in next_chunk
    return self._process_response(resp, content)
  File "C:\Users\...\testapp\apiclient\http.py", line 901, in _process_response
    raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 400 when requesting https://www.googleapis.com/upload/youtube/v3/videos?alt=json&part=status%2Csnippet&uploadType=resumable returned "Bad Request">

解决方案

Whether it is the best approach or not is really for you to figure out. But using argparse without command line is easy. I do it all the time because I have batches that can be run from the command line. Or can also be called by other code - which is great for unit testing, as mentioned. argparse is especially good at defaulting parameters for example.

Starting with your sample.

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument("--file", required=True, help="Video file to upload")
argparser.add_argument("--title", help="Video title", default="Test Title")
argparser.add_argument("--description", help="Video description",
    default="Test Description")
argparser.add_argument("--category", default="22",
    help="Numeric video category. " +
        "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
argparser.add_argument("--keywords", help="Video keywords, comma separated",
    default="")
VALID_PRIVACY_STATUSES = ("private","public")
argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
    default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")

#pass in any positional or required variables.. as strings in a list
#which corresponds to sys.argv[1:].  Not a string => arcane errors.
args = argparser.parse_args(["--file", "myfile.avi"])

#you can populate other optional parameters, not just positionals/required
#args = argparser.parse_args(["--file", "myfile.avi", "--title", "my title"])


print vars(args)

#modify them as you see fit, but no more validation is taking place
#so best to use parse_args.
args.privacyStatus = "some status not in choices - already parsed"
args.category = 42

print vars(args)

#proceed as before, the system doesn't care if it came from the command line or not
# youtube = get_authenticated_service(args)    

output:

{'category': '22', 'description': 'Test Description', 'title': 'Test Title', 'privacyStatus': 'private', 'file': 'myfile.avi', 'keywords': ''}
{'category': 42, 'description': 'Test Description', 'title': 'Test Title', 'privacyStatus': 'some status not in choices - already parsed', 'file': 'myfile.avi', 'keywords': ''}

这篇关于python argparse - 在没有命令行的情况下传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆