gpt4 book ai didi

python argparse - 在没有命令行的情况下传递值

转载 作者:太空狗 更新时间:2023-10-29 20:49:36 25 4
gpt4 key购买 nike

我想我不了解 python 的 argparse 的一些基本知识。

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

例如,here是 API 的示例。 github 和其他地方的示例显示此示例是从命令行调用的,在调用脚本时从命令行传递 argparse 值。

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

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

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)

编辑:根据请求,这是我使用标准方法初始化字典或使用 argparse 创建字典时遇到的 400 错误的回溯。我以为我得到这个是因为参数格式不正确,但也许不是:

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">

最佳答案

这是否是最佳方法真的需要您自己判断。但是在没有命令行的情况下使用 argparse 是简单的。我一直这样做,因为我有可以从命令行运行的批处理。或者也可以被其他代码调用——如前所述,这非常适合单元测试。例如,argparse 特别擅长默认参数。

从您的样本开始。

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)

输出:

{'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 - 在没有命令行的情况下传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com