Python Forum
accept command line argument
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
accept command line argument
#1
Hi Team,

how to accept multiple values or a list of values from command prompt. and store into single variable.

folderpath, next list of file names to delete.

accept "ab,xy,py,cd,ef,gh" and store into single variable.

**python test.py "C:/Users/malle/OneDrive/Desktop/C/test_data" "ab,xy,py,cd,ef,gh"**

from pathlib import Path
import sys

def remove_files(folderpath, files):
    import os
    os.chdir(folderpath)
    collection = []
    collection = files.split(",")
    for coll in collection:
        files = Path.cwd().glob(f"*{coll}*")
        for file in files:
            file.unlink(missing_ok=True)
	

if __name__ == "__main__":
    pattern = "ab,xy,py,cd,ef,gh"
    root = "C:/Users/malle/OneDrive/Desktop/C/test_data"
    remove_files(root, pattern)
snippsat write Sep-26-2022, 12:14 PM:
Added code tag in your post,look at BBCode on how to use.
Reply
#2
(Sep-26-2022, 11:34 AM)mg24 Wrote: Hi Team,

how to accept multiple values or a list of values from command prompt. and store into single variable.

folderpath, next list of file names to delete.

accept "ab,xy,py,cd,ef,gh" and store into single variable.

**python test.py "C:/Users/malle/OneDrive/Desktop/C/test_data" "ab,xy,py,cd,ef,gh"**

from pathlib import Path
import sys

def remove_files(folderpath, files):
    import os
    os.chdir(folderpath)
    collection = []
    collection = files.split(",")
    for coll in collection:
        files = Path.cwd().glob(f"*{coll}*")
        for file in files:
            file.unlink(missing_ok=True)
	

if __name__ == "__main__":
    pattern = "ab,xy,py,cd,ef,gh"
    root = "C:/Users/malle/OneDrive/Desktop/C/test_data"
    remove_files(root, pattern)

You could use sys.argv for that!

import sys

"""
sys.argv returns a list object containing all the arguments passed when
running your script, including the script itself.

In this case, running the command python test.py "ab,xy,py,cd,ef,gh"
will return: ['test.py', 'ab,xy,py,cd,ef,gh']

If, instead of the list of values enclosed in double quotes you pass
the individual values separated by spaces, you will get a list with
the script name plus every value you passed.

python test.py ab xy py cd ef gh
will return: ['test.py', 'ab', 'xy', 'py', 'cd', 'ef', 'gh']

Than you can get only the values you want using list comprehension:
values = sys.argv[1:]

The above gets all the values from sys.argv except the first index,
which is the script file. 
"""

arguments = sys.argv
values = arguments[1:]

print(values)
Reply
#3
I would advice a library for building CLI applications,over using sys.argv.
Typer is easy to use and really good.
Here a example with your code.
# file_rm.py
from pathlib import Path
import sys
import os
import typer

app = typer.Typer()

@app.command()
def remove_files(folderpath: str, files: str):
    '''Remove files based on patrtern given'''
    os.chdir(folderpath)
    collection = []
    collection = files.split(",")
    for coll in collection:
        files = Path.cwd().glob(f"*{coll}*")
        for file in files:
            print(file) # Test print before delete
            #file.unlink(missing_ok=True)

if __name__ == "__main__": 
    app()
So now will get help generated automatic.
λ python file_rm.py --help

 Usage: file_rm.py [OPTIONS] FOLDERPATH FILES

 Remove files based on patrtern given

┌─ Arguments ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ *    folderpath      TEXT  [default: None] [required]                                                                                                                       │
│ *    files           TEXT  [default: None] [required]                                                                                                                       │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Options ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ --install-completion        [bash|zsh|fish|powershell|pwsh]  Install completion for the specified shell. [default: None]                                                    │
│ --show-completion           [bash|zsh|fish|powershell|pwsh]  Show completion for the specified shell, to copy it or customize the installation. [default: None]             │
│ --help                                                       Show this message and exit.                                                                                    │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Test that his work.
G:\div_code\answer\mb
# Now give argument after file
λ python file_rm.py C:/test_data ab,xy,py,cd,ef,gh
C:\test_data\ab11.tx
carecavoador likes this post
Reply
#4
Hi snippsat,

Superb ! it worked as expected ! Clap

is there any other way we can achieve this.

without using global keyboard.
files = Path.cwd().glob(f"*{coll}*") just for learning purpose.

@app.command() what this line mean.
Reply
#5
Click on the typer link and read about @app.command()
Reply
#6
(Sep-27-2022, 10:03 AM)mg24 Wrote: without using global keyboard.
files = Path.cwd().glob(f"*{coll}*") just for learning purpose.
Hmm global keyboard? maybe you meant global keyword.
It not a global keyword and it's ok to use like this.
Path.glob a trick it to make make it recursively is to add **.
files = Path.cwd().glob(f"**/{coll}*")
(Sep-27-2022, 10:03 AM)mg24 Wrote: @app.command() what this line mean
It's a decorator this mean that can get a clean interface and hide all code that needed in background.
The author of Typer is also author of FastAPI where you see same decorator pattern.
Flask was one the library's first that used this way pattern a lot.
Flask
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}
Typer.
import typer

app = typer.Typer()

@app.command()
def hello(name: str):
    print(f"Hello {name}")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Command line argument issue space issue mg24 5 1,279 Oct-26-2022, 11:05 PM
Last Post: Yoriz
  Accessing varying command line arguements Rakshan 3 2,008 Jul-28-2021, 03:18 PM
Last Post: snippsat
  How to input & output parameters from command line argument shantanu97 1 2,505 Apr-13-2021, 02:12 PM
Last Post: Larz60+
  Passing List of Objects in Command Line Python usman 7 3,084 Sep-27-2020, 03:45 PM
Last Post: ndc85430
  I need my compiled Python Mac app to accept a file as a parameter Oethen 2 2,357 May-10-2020, 05:57 PM
Last Post: Oethen
  Taking Multiple Command Line Argument Input bwdu 6 3,921 Mar-29-2020, 05:52 PM
Last Post: buran
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,728 Mar-03-2020, 08:34 AM
Last Post: buran
  python 3 from command line Dixon 1 1,964 Mar-01-2020, 08:35 PM
Last Post: snippsat
  Running linux command line apps... dbrdh 0 1,619 Jan-30-2020, 01:14 PM
Last Post: dbrdh
  command line input (arg parse) and data exchange Simba 7 4,242 Dec-06-2019, 11:58 PM
Last Post: Simba

Forum Jump:

User Panel Messages

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