Python Forum

Full Version: Take inline argument value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All ,
I need help in modifying a Script
I need help in python syntax , where I would like to take value from inline argument .

for e.g : lets say
1) I will pass an argument “-rundir my_name_folder “ in my command line
2) My script should detect an argument is passed : -rundir
3) Then it will store its value in some variable [ I am not sure of this part ] , value = my_name_folder
4) Then it will create a directory in current working directory with name my_name_folder

Thanks in advance
For something simple like this you can use the standard argparse library.

https://docs.python.org/3/library/argparse.html
The simple and limited way is to use sys.argv.
In stander library eg argparse

I would suggest Typer (it's build on Click but make it even easier to use).
Both are good Click has been my favorite for a long time.
Typer take advantage of Python type hints,and use it as useful feature.
Example
import typer
import pathlib

def make(folder_name: str):
    '''Make a new folder in current folder'''
    typer.echo(f"Make new folder: {folder_name}")
    new_folder = pathlib.Path(folder_name)
    new_folder.mkdir(parents=True, exist_ok=True)

if __name__ == "__main__":
    typer.run(make)

From command line.
G:\div_code\answer\temp
λ python rundir.py --help
Usage: rundir.py [OPTIONS] FOLDER_NAME

  Make a new folder in current folder

Arguments:
  FOLDER_NAME  [required]

Options:
  --install-completion [bash|zsh|fish|powershell|pwsh]
                                  Install completion for the specified shell.
  --show-completion [bash|zsh|fish|powershell|pwsh]
                                  Show completion for the specified shell, to
                                  copy it or customize the installation.
  --help                          Show this message and exit.

# Make 
G:\div_code\answer\temp
λ python rundir.py images
Make new folder: images

# List
G:\div_code\answer\temp
λ ls
images/  rundir.py
See that get --help for free,this should always a CLI(command line interfaces) has as argument.