Python Forum
problem in output of a snippet code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem in output of a snippet code
#1
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
Reply
#2
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]
Reply
#3
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')
akbarza likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  output shape problem with np.arange alan6690 5 702 Dec-26-2023, 05:44 PM
Last Post: deanhystad
  problem in output of a function akbarza 9 1,212 Sep-29-2023, 11:13 AM
Last Post: snippsat
  I cannot able to see output of this code ted 1 762 Feb-22-2023, 09:43 PM
Last Post: deanhystad
  Python Pandas Syntax problem? Wrong Output, any ideas? Gbuoy 2 937 Jan-18-2023, 10:02 PM
Last Post: snippsat
  Facing problem with Pycharm - Not getting the expected output amortal03 1 865 Sep-09-2022, 05:44 PM
Last Post: Yoriz
  [Solved] Trying to rerun a snippet of code paracel 3 1,163 Jul-17-2022, 01:49 PM
Last Post: paracel
  why I dont get any output from this code William369 2 1,138 Jun-23-2022, 09:18 PM
Last Post: William369
  Can someone explain this small snippet of code like I am a 5 year old? PythonNPC 3 1,250 Apr-08-2022, 05:54 PM
Last Post: deanhystad
  How can I organize my code according to output that I want ilknurg 1 1,182 Mar-11-2022, 09:24 AM
Last Post: perfringo
  single input infinite output problem Chase91 2 1,957 Sep-23-2020, 10:01 PM
Last Post: Chase91

Forum Jump:

User Panel Messages

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