Joseleg
Joseleg

Reputation: 393

Error executing python scripts

When I try to execute a python script with arguments, the script fails and show the following error:

-bash: syntax error near unexpected token `"Lary",'

I try to execute the script like this:

display("Lary", 43, "M")

My code

#! /usr/bin/python

def display(name, age, sex):
  print "Name: ", name
  print "Age: ", age
  print "Sex: ", sex

I try setting execute rights to the script (chmod 755 test.py) and I always get the same error.

What is wrong?

Upvotes: 0

Views: 1286

Answers (4)

SVatasoiu
SVatasoiu

Reputation: 171

If I understand correctly, you want to run something like:

    ./test.py "Lary" 43 "M"

from the command line. To do this, you set the permissions correctly. But you need to access the command line arguments using the sys module:

    #! /usr/bin/python
    import sys

    def display(name, age, sex):
      print "Name: ", name
      print "Age: ", age
      print "Sex: ", sex

    display(sys.argv[1],sys.argv[2],sys.argv[3])

sys.argv returns a list of the command line arguments with the name of the file being sys.argv[0] (in this case ./test.py). Of course, you should probably have some sort of argument checking making sure there are enough arguments, etc. Also, make sure to parse the commands correctly. For example, if age is supposed to be an integer, you need to do age = int(sys.argv[2]) as sys.argv is a list of strings, as is standard in most languages.

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You do not execute a script calling the function display("Lary", 43, "M")

you use python my_script.py from bash or ./my_script.py

You are getting a bash error not a python error, to make a python script executable you just need chmod +x my_script.py.

~$ display("Lary", 43, "M")
bash: syntax error near unexpected token `"Lary",'

my_script.py:

import sys

def display(name, age, sex):
  print "Name: ", name
  print "Age: ", age
  print "Sex: ", sex
name = sys.argv[1]
age = sys.argv[2]
sex = sys.argv[3]
display(name, age, sex)

~$ python my_script.py foo 43 male
Name:  foo
Age:  43
Sex:  male

Upvotes: 0

Tom Dalton
Tom Dalton

Reputation: 6190

If you want to pass arguments to a python program, the simplest way is with sys.argv:

my_program.py:

#!/usr/bin/env python
import sys

print "Arguments passed:"
print sys.argv

Then run your program like:

./my_program.py this is "A test" 1 2 3

Upvotes: 0

DSM
DSM

Reputation: 353019

That error message means you're calling your function from the bash shell:

dsm@winter:~/coding$ display("Lary", 43, "M")
bash: syntax error near unexpected token `"Lary",'

You need to call it from the Python console:

dsm@winter:~/coding$ python -i display.py
>>> display("Larry", 43, "M")
Name:  Larry
Age:  43
Sex:  M

You can't really call Python functions from the bash console the way you're trying.

Upvotes: 1

Related Questions