Home > OS >  Adding "argparser.add_argument()" in script
Adding "argparser.add_argument()" in script

Time:11-21

I am coding something using the YouTubeV3 API to upload a video. I was going through the demo script Google gives, but don't fully understand this piece of code. It uses argparser.add_argument() to add information like the file or title through the command line, however I want to add this info in the script itself. How do I do this?

I have tried setting the value by using the "default" attribute, however this doesn't work in a loop, as you end up adding it twice. I cant find anything about this online.

Here is a basic verison of the code with print statements to show what the values are:

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

Here is the output (I change the value of "auth_host_port", dont think I needed to censor it but better safe then sorry):

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

CodePudding user response:

Python's argparse library is a library used to build CLI (Command Line Interfaces) - meaning you pass variables into the program through the command line. Read more about argparse here: https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3

If you do not wish to program it as a CLI, simply make the adjustments you need. For example, instead of doing this:

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

Do this:

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

CodePudding user response:

I finally figured it out, its actaully really simple.

You can just do args.[varaible] = [value] e.g. args.file = "video.mp4" or args.title = "hello world"

You dont need to create the varaible first, just args.[varaible] = [value] and it will add that new varaible to args

  • Related