benst
benst

Reputation: 553

Command line arguments passing in python

Hi I am new to Python and have currently copied following script:

# filename is printer.py
import sys
for arg in sys.argv:
    print arg    # the zeroth element is the module name
raw_input("press any key")    # a trick to keep the python console open

I am trying to get the arguments followed by the module name. But running this code gives me following error:

U:\printer.py
    File "U:\printer.py", line 6
      print arg # zeroth element is the module name
              ^
SyntaxError: Invalid syntax

Does anyone know what could be wrong here? I am using Python 3.2

Upvotes: 0

Views: 372

Answers (3)

mgilson
mgilson

Reputation: 309831

As noted by others, in python3, print is a function:

print arg

is now:

print(arg)

Also, raw_input is gone and replaced by simply input. (in py2k, input would eval the string from the commandline, but it won't do that in py3k).


Finally (and maybe most importantly), have you considered argparse? (untested code follows)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo',nargs='*',help="What a nice day we're having")
args = parser.parse_args()
print(args.foo)

Upvotes: 5

user647772
user647772

Reputation:

In Python 3 print is a function:

print(arg)

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409136

Python 3 no longer has a print keyword, but a print function.

Try instead

print(arg)

Upvotes: 2

Related Questions