Link to home
Start Free TrialLog in
Avatar of ReneGe
ReneGeFlag for Canada

asked on

Python 2.7 - Passing arguments

Hi there,

From the windows shell, I need to start my project by passing an argument to it.

Command line: task.py "These are strings" "9"
Where 9 is a number

print "argument1"
type (argument1)
print("") #CLRF is intended here

print argument2 + 100
type (argument2)

Open in new window


Thanks for your help,
Rene
Avatar of gelonida
gelonida
Flag of France image

what you are looking foir is sys.argv, which works for windows and other OSes

import sys
args = sys.argv[1:]
if len(args) < 2:
    print("ERROR: at least 2 arguments required, but got only %d"  % len(args))
    sys.exit(1)

argument1, argument2  = args[:2]
argument2 = int(argument2)

print("argument1 %r" % argument1)
print("") #CLRF is intended here

print(int(argument2) + 100)

Open in new window


you might also look at a much more complex but very flexible solution for parsing command line arguments.

the module is called https://docs.python.org/3/library/argparse.html
it is used to parse / validate sys.argv[1:]
Avatar of ReneGe

ASKER

Hi Gelonida,

Thanks for your prompt response :)

Here is the output I got:
ERROR: at least 2 arguments required, but got only 0

My command line was: task.py "qq" "9"

Cheers
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ReneGe

ASKER

Yea it's working

I omitted to add python in my command line :)

I'll know better next time!

Thanks for your help
Cheers
Good to know that you got it working.

However on my Windows machine I'm not obliged to type python before the command.

I guess, that your python launcher is not configured as it should be.
Avatar of ReneGe

ASKER

Maybe I should associate .py extensions to my python.exe
Avatar of ReneGe

ASKER

Did not work!  Oh well, I guess I can create a new question for this one as well
Thanks :)