Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Take inline argument value
#1
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
Reply
#2
For something simple like this you can use the standard argparse library.

https://docs.python.org/3/library/argparse.html
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I have an index error inline 76 but I write the program in a way that cant reach tha abbaszandi 2 2,076 Nov-13-2020, 07:43 AM
Last Post: buran
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,858 Mar-03-2020, 08:34 AM
Last Post: buran
  To correct inline or not to correct inline burningkrome 3 2,123 Oct-03-2019, 01:12 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020