[Tutor] passing named arguments through command line

Lukas Nemec lu.nemec at gmail.com
Thu Oct 30 15:58:19 CET 2014


Hello,

take a look at argparse library.

-------
import argparse

parser = argparse.ArgumentParser(description="My prgoram")
parser.add_argument('-y', '--y', help="Y value", required=True)
parser.add_argument('-x', '--x', help="X value", required=True)


def main(x=1, y=2):
     print x
     print y


if __name__ == '__main__':
     args = parser.parse_args()
     main(x=args.x, y=args.y)


Enjoy!
Lukas

On 10/30/2014 03:01 PM, Robert Sokolewicz wrote:
> I have a function with optional arguments x, y and I would like to 
> pass y or z using a named variable through the command line. Inside a 
> python script main(y=3) would work, but I have trouble passing y=3 as 
> an argument in command line.
>
> I have tried the following:
>
> ----
> import sys
>
> def main(x=1, y=2):
>    print x
>    print y
>
> if __name__ == '__main__':
> main(*sys.argv[1:])
>
> -----
>
> from my terminal I get:
>
> $ python script.py
> 1
> 2
> $ python script.py y=3
> y=3
> 2
>
> whereas I would like the following to happen:
> $ python script.py y=3
> 1
> 3
>
> Is this doable in any convenient way?
>
> thanks in advance!
>
> -Robert
>
>
>
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141030/b5d1feb7/attachment.html>


More information about the Tutor mailing list