Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python argparse-不使用命令行传递值_Python_Google Api_Youtube Api_Argparse - Fatal编程技术网

python argparse-不使用命令行传递值

python argparse-不使用命令行传递值,python,google-api,youtube-api,argparse,Python,Google Api,Youtube Api,Argparse,我想我对python的argparse还不太了解 我试图使用Google YouTube API for python脚本,但我不理解如何在不使用命令行的情况下将值传递给脚本 例如,是API的示例。github和其他地方的示例显示,这个示例是从命令行调用的,在调用脚本时,argparse值是从命令行传递的 我不想使用命令行。我正在构建一个应用程序,它使用一个装饰程序来获取用户的登录凭据,当用户想要上传到他们的YouTube帐户时,他们会提交一个表单,然后调用这个脚本并将argparse值传递给它

我想我对python的argparse还不太了解

我试图使用Google YouTube API for python脚本,但我不理解如何在不使用命令行的情况下将值传递给脚本

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

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

如何从另一个python脚本将值传递给argparser(YouTube upload 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">
回溯(最近一次呼叫最后一次):
文件“C:\Program Files(x86)\Google\Google\U appengine\lib\webapp2-2.5.2\webapp2.py”,第1535行,在调用中__
rv=自身处理异常(请求、响应、e)
文件“C:\Program Files(x86)\Google\Google\U appengine\lib\webapp2-2.5.2\webapp2.py”,第1529行,在调用中__
rv=自我路由器调度(请求、响应)
默认情况下,文件“C:\Program Files(x86)\Google\Google\u appengine\lib\webapp2-2.5.2\webapp2.py”第1278行
返回路由处理程序适配器(请求、响应)
文件“C:\Program Files(x86)\Google\Google\u appengine\lib\webapp2-2.5.2\webapp2.py”,第1102行,在调用中__
返回处理程序.dispatch()
文件“C:\Program Files(x86)\Google\Google\U appengine\lib\webapp2-2.5.2\webapp2.py”,第572行,在调度中
返回self.handle_异常(e,self.app.debug)
文件“C:\Program Files(x86)\Google\Google\U appengine\lib\webapp2-2.5.2\webapp2.py”,第570行,在调度中
返回方法(*args,**kwargs)
文件“C:\Users\…\testapp\oauth2client\appengine.py”,第796行,在setup\u oauth中
resp=方法(请求处理程序,*args,**kwargs)
get中第116行的文件“C:\Users\…\testapp\testapp.py”
可恢复上传(插入请求)
文件“C:\Users\…\testapp\testapp.py”,第183行,可恢复上传
状态,响应=插入请求。下一个\u块()
文件“C:\Users\…\testapp\oauth2client\util.py”,第129行,在位置包装中
已包装退货(*args,**kwargs)
文件“C:\Users\…\testapp\apiclient\http.py”,第874行,在下一个\u块中
返回自我。\处理\响应(响应、内容)
文件“C:\Users\…\testapp\apiclient\http.py”,第901行,在进程响应中
raise HttpError(resp,content,uri=self.uri)
HttpError:

如果不想使用命令行,为什么要使用argparse?Argparse是为解析命令行参数而创建的模块,它没有其他用途。不能以其他方式将值传递给argparse


我认为您需要的是一个web应用程序,它显示html表单,向某个服务器处理程序发出POST请求,该服务器处理程序将值从表单传递到api调用,并连接到youtube,然后执行python代码。这根本不需要Argparse。您只需从表单中获取值并将其传递给您的api调用。

这是否是最好的方法实际上需要您自己来确定。但是在没有命令行的情况下使用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': ''}

使用自己的字符串列表调用
parse_args
是一种常见的
argparse
测试方法。如果您没有给出此列表的
parse_args
,它将使用
sys.argv[1:][/code>——即shell给出的字符串
sys.argv[0]
是条带名称

args = argparser.parse_args(['--foo','foovalue','barvalue'])
构造
args
对象也很容易

args = argparse.Namespace(foo='foovalue', bar='barvalue')
事实上,如果从
parse_args
调用打印
args
,它应该是这样的。如文档中所述,
名称空间
是一个简单的对象,其值是artributes。因此,很容易构造自己的
命名空间
类。所有
args
都必须是在用作以下对象时返回适当值的对象:

x = args.foo
b = args.bar
同样如文档中所述,
vars(args)
将此名称空间转换为字典。有些代码喜欢使用dictionary,但显然这些youtub函数需要一个
名称空间
(或等效名称空间)


拥有
获取经过身份验证的\u服务
初始化\u上传
代码

def initialize_upload(youtube, options):
  tags = None
  if options.keywords:
    tags = options.keywords.split(",")

  body=dict(
    snippet=dict(
      title=options.title,
      description=options.description,
      tags=tags,
      categoryId=options.category
    ),
    status=dict(
      privacyStatus=options.privacyStatus
    )
  )
 ....

解析器中的
args
options
,它用作
options.category
options.title
等。您可以替换具有相同行为和必要属性的任何其他对象

最简单的方法是重构代码,以便将
sys.argv
显式传递给使用
argparse
处理结果列表的函数;这也使得测试更加简单。请看,这里只有一个大问题,如果您不使用命令行,为什么需要解析命令行参数?您只需从google站点复制粘贴示例,而不了解代码本身。虽然我是python新手,但我正在尝试理解代码,这就是为什么我尝试了一种不同的字典创建方法。我想这两种方法都有效。我很感激人们试图帮助我更好地理解argparse方法。因为无论哪种方法,我都会得到400个错误,我显然还有更多的东西要学
def initialize_upload(youtube, options):
  tags = None
  if options.keywords:
    tags = options.keywords.split(",")

  body=dict(
    snippet=dict(
      title=options.title,
      description=options.description,
      tags=tags,
      categoryId=options.category
    ),
    status=dict(
      privacyStatus=options.privacyStatus
    )
  )
 ....