【问题标题】:Adding "argparser.add_argument()" in script在脚本中添加 \"argparser.add_argument()\"
【发布时间】:2022-11-21 01:45:07
【问题描述】:

我正在使用 YouTubeV3 API 编写一些代码来上传视频。我正在浏览 Google 提供的演示脚本,但没有完全理解这段代码。它使用 argparser.add_argument() 通过命令行添加文件或标题等信息,但我想在脚本本身中添加此信息。我该怎么做呢?

我曾尝试使用“默认”属性设置该值,但这在循环中不起作用,因为您最终添加了两次。我在网上找不到任何关于此的信息。

这是代码的基本版本,带有打印语句以显示值是什么:

argparser.add_argument("--file", default="video.mp4")
argparser.add_argument("--title", default="hello world")
print(f"argparser:\n{argparser}\n")
print(f"argparser.parse_args():\n{argparser.parse_args()}\n")
args = argparser.parse_args()
print(f"args:\n{args}\n")

这是输出(我更改了“auth_host_port”的值,我认为我不需要审查它但更安全然后抱歉):

argparser:
ArgumentParser(prog='script.py', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=False)

argparser.parse_args():
Namespace(auth_host_name='localhost', noauth_local_webserver=False, auth_host_port=[0000, 0000], logging_level='ERROR', file='video.mp4', title='hello world')

args:
Namespace(auth_host_name='localhost', noauth_local_webserver=False, auth_host_port=[0000, 0000], logging_level='ERROR', file='video.mp4', title='hello world')

【问题讨论】:

    标签: python python-3.x youtube-api argparse


    【解决方案1】:

    Python 的argparse 库是一个用于构建 CLI(命令行界面)的库——这意味着您可以通过命令行将变量传递到程序中。 在此处阅读有关 argparse 的更多信息:https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3

    如果您不想将其编程为 CLI,只需进行所需的调整即可。例如,而不是这样做:

    print(f"Video title: {argparser.title}")
    # This stores the "--title" argument you pass in through the command line.
    # If you do not pass a title argument, it takes the default value.
    # In your case, it will be "hello world", as you specified in the second line
    

    做这个:

    title = "My video title"
    print(f"Video title: {title}")
    

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2015-05-29
      • 2020-06-27
      • 2015-06-22
      • 2012-07-20
      相关资源
      最近更新 更多