Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How argv works?
#1
Here argv is a tuple. That inputs name of two persons 'John' and 'Jack' one by one.

And prints out "Hi, John" first time and "Hi Jack" second time.
This code works. But I am not sure how it works. It would be helpful if someone could tell me step by step what it is doing.

The Code:
import sys
def main(argv):
    for key, value in enumerate(argv):
        print("Hi, {1}".format(key, value))        #I have no Idea what's happening here
if __name__=='main':
    main(sys.argv[1:])                             #Not sure what happens here either
Reply
#2
This will help, (checks python version, if >= 3.6 uses f-string else format)
sys.argv[0] is always script name (__file__)
remaining args are what's typed on command line after script name, or another way to look at it is:
argv is a list of what's typed on command line:
import sys

python_version = sys.version.split()[0]

if python_version > '3.5':
    print(f'You are running python version: {python_version}, so can use f-string')

    for n, item in enumerate(sys.argv):
        print(f'Argv{n} = {sys.argv[n]}')
else:
    print('You are running python version: {}, so cannot use f-string'.format(python_version))

    for n, item in enumerate(sys.argv):
        print('Argv{} = {}'.format(n, argv[n]))
for command:
python -u ".../TryStuff/src/Args/TryArgs.py" Hup two threefour -z
results in:
Output:
You are running python version: 3.7.1, so can use f-string Argv0 = /media/larz60/Data-2TB/Projects/TryStuff/src/Args/TryArgs.py Argv1 = Hup Argv2 = two Argv3 = three Argv4 = four Argv5 = -z
Reply
#3
(Dec-25-2018, 03:25 PM)Larz60+ Wrote: This will help, (checks python version, if >= 3.6 uses f-string else format)
sys.argv[0] is always script name (__file__)
remaining args are what's typed on command line after script name, or another way to look at it is:
So the key, value pairs in argv are the index and the value? With the first[0] index being the file name, and rest the arguments?
main(sys.argv[1:])  
This line executes for first argument(not-filename) passed from CLI? Which here is 'John'.
Prints out
print("Hi, {1}".format(key, value)) 
Then does the same thing all over again for the second argument passed from CLI? Which is 'Jack'.

I'm a bit confused, how it is working.
Thanks for the help.
Reply
#4
The original code:
import sys
def main(argv):
    for key, value in enumerate(argv):
        print("Hi, {1}".format(key, value))        #I have no Idea what's happening here
if __name__=='main':
    main(sys.argv[1:])                             #Not sure what happens here either
is better written as:
import sys

def main(argv):
    for item in argv:
        print("Hi, {}".format(item))

if __name__ == '__main__':
    main(sys.argv[1:])
this code: main(sys.argv[1:]) slices off the 1st argument, passing the remainder to main
Using key, value implies a dictionary, argv is a list, not a dictionary, and should be treated as such.

In post # 2, I show both format and f-string.
format is just a way of providing the arguments to the {} in the string.
f-string is capable of doing this inline which is much better, but requires python 3.6 or newer.

Botton line: argv is a list ... Not a dictionary ther are no key, value pairs!
Reply
#5
Okay, Understood.

(Dec-25-2018, 05:51 PM)Larz60+ Wrote: passing the remainder to main
Does it pass one by one?
I mean, executes for argv[1] then argv[2] like this?
Reply
#6
Its a new list that strips off the first element (the filename) and only gives th arguments..

It should be noted that most people in python dont make their own argument parser from sys.argv, but use a builtin module called argparse because its more efficient.
Recommended Tutorials:
Reply
#7
Here's what argparse looks like (this is just a shell example). I didn't want to get into it because I
thought it would complicate things, but might as well be introduced to it now:

import sys
import argparse
import optparse


class JustMakePretty:
    def __init__(self):
        pass

    def prettify(self, infile, outfile):
        print(f'infile: {infile}, outfile: {outfile}')

def process_args():
    jmp = JustMakePretty()
    # _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None
    parser = optparse.OptionParser('usage%prog' + ' -i ' + '<infilename>' +' -o ' + '<outfilename>')
    # parser = argparse.ArgumentParser()
    parser.add_option('-i', dest='infilename', help='The input html filename.')
    parser.add_option('-o', dest='outfilename', help='The input html filename.')
    (options,args) = parser.parse_args()

    infilename  = options.infilename
    outfilename = options.outfilename
    
    jmp.prettify(infilename, outfilename)

if __name__ == '__main__':
    process_args()
so some usage:
python usageJustMakePretty.py -h
output:
Output:
Usage: usageJustMakePretty.py -i <infilename> -o <outfilename> Options: -h, --help show this help message and exit -i INFILENAME The input html filename. -o OUTFILENAME The input html filename.
python usageJustMakePretty.py -i infile_a.txt -o outfile_b.txt
output:
Output:
infile: infile_a.txt, outfile: outfile_b.txt
Reply
#8
Argparse is actually preferred over optparse. It is depreciated since 3.2

https://docs.python.org/3.6/library/optparse.html

Here is an intro to argparse

https://www.pythonforbeginners.com/argpa...e-tutorial
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 795 May-02-2023, 08:40 AM
Last Post: Gribouillis
  sys.argv method nngokturk 3 1,089 Jan-23-2023, 10:41 PM
Last Post: deanhystad
  import argv Scott 3 5,905 Apr-01-2021, 11:03 AM
Last Post: radix018
  use of sys.argv deepakkr3110 3 3,050 Nov-29-2019, 05:41 AM
Last Post: buran
  Not all data returned from sys.argv ecdhyne 2 2,769 Sep-05-2019, 08:27 PM
Last Post: buran
  Pyinstaller with Sys.Argv[] - “Failed to Execute Script”? ironfelix717 0 5,310 Aug-07-2019, 02:29 PM
Last Post: ironfelix717
  I see is that sys.argv contains character strings helenharry 2 2,759 Jan-09-2019, 11:34 AM
Last Post: DeaD_EyE
  sys.argv correct sintax? enricosx 3 3,215 Jul-25-2018, 09:27 AM
Last Post: buran
  I gotta problem with making argv parameters Bozx 3 4,060 Apr-04-2017, 03:44 AM
Last Post: alicarlos13
  argv IndexError hsunteik 2 4,538 Dec-19-2016, 06:19 AM
Last Post: hsunteik

Forum Jump:

User Panel Messages

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