Posts: 11
Threads: 4
Joined: Apr 2018
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
Posts: 12,032
Threads: 486
Joined: Sep 2016
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
Posts: 11
Threads: 4
Joined: Apr 2018
(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.
Posts: 12,032
Threads: 486
Joined: Sep 2016
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!
Posts: 11
Threads: 4
Joined: Apr 2018
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?
Posts: 5,151
Threads: 396
Joined: Sep 2016
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:
Posts: 12,032
Threads: 486
Joined: Sep 2016
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
Posts: 5,151
Threads: 396
Joined: Sep 2016
Dec-26-2018, 12:20 AM
(This post was last modified: Dec-26-2018, 12:20 AM by metulburr.)
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:
|