Python Forum

Full Version: problem in output of a snippet code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
assume the below snippet code(the code address is in the docstring of the code) :
 ''' from:https://www.knowledgehut.com/blog/programming/sys-argv-python- examples#what-is-%22sys.%C2%A0argv%C2%A0[1]%22?-how-does%C2%A0it-work?%C2%A0 ''' import getopt import sys first ="" last ="" argv = sys.argv[1:] try: options, args = getopt.getopt(argv, "f:l:", ["first =", "last ="]) except: print("Error Message ") for name, value in options: if name in ['-f', '--first']: first = value elif name in ['-l', '--last']: last = value print(first + " " + last) # in cmd write: python getopt_module.py -f Knowledge -l Hut # or # in cmd write: python getopt_module.py --first Knowledge --last Hut #### but the last line does not show anything in output, why?
after saving this file as getopt_module.py, if I write in cmd:
python getopt_module.py -f Knowledge -l Hut
The output will be:
Output:
Knowledge Hut
but if write in cmd:
python getopt_module.py --first Knowledge --last Hut
then nothing will be in the output. why?
thanks
Do not use getop.
Doc Wrote:PEP 387 defines "Soft Deprecation", getopt and optparse are soft deprecated
In stander library use argparse.
So if rewrite it look like this:
# file: arg_ex.py import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-f', '--first', type=str, help='First name') parser.add_argument('-l', '--last', type=str, help='Last name') args = parser.parse_args() # Use the arguments first = args.first if args.first else "" last = args.last if args.last else "" print(f'{first} {last}')
Usage command line:
Output:
λ python arg_ex.py --help usage: arg_ex.py [-h] [-f FIRST] [-l LAST] Get Names options: -h, --help show this help message and exit -f FIRST, --first FIRST First name -l LAST, --last LAST Last name C:\code\cv_test λ python arg_ex.py -f Tom Tom C:\code\cv_test λ python arg_ex.py --first Kent --last Superman Kent Superman

There are also good 3-party libraries for this like eg Typer
To show a example that i posted before.
# file: rename_files.py from pathlib import Path import typer app = typer.Typer() @app.command() def renameit( old_name: str = typer.Option(..., '-o', '--old-name'), new_name: str = typer.Option(..., '-n', '--new-name'), ): old_path = Path(old_name) if old_path.is_file(): old_path.rename(Path(new_name)) typer.echo(f'File renamed from {old_name} to {new_name}') else: typer.echo('File not found.') if __name__ == '__main__': app() 
Using it,see that help and colors(use Rich under the hood) get generated automatic.
[Image: ATaLiF.png]
This line was wrong.
options, args = getopt.getopt(argv, "f:l:", ["first =", "last ="])
It should be
options, args = getopt.getopt(argv, "f:l:", ["first=", "last="])
from getopt import getopt def getargs(argv): options, args = getopt(argv, "f:l:", ["first=", "last="]) options = dict(options) return ( options.get('--first', options.get('-f')), options.get('--last', options.get('-l')), *args ) print(getargs("-f Knowledge -l Hut".split())) print(getargs("--first Knowledge --last Hut".split())) print(getargs("-f Knowledge --last Hut".split())) print(getargs("-f Knowledge --last Hut arg1 arg2".split()))
Output:
('Knowledge', 'Hut') ('Knowledge', 'Hut') ('Knowledge', 'Hut') ('Knowledge', 'Hut', 'arg1', 'arg2')