2
#!/usr/bin/python

import os
import shutil
import commands
import time
import copy

name = 'test'

echo name 

I have a simple python scripts like the above. When I attempt to execute it I get a syntax error when trying to output the name variable.

5
  • 3
    You should at least specify the exact error message you're obtaining. Commented Jun 5, 2012 at 21:47
  • 2
    Why did you expect a generic unix command (echo) to be supported just like that in Python as if it was a recognized Python statement? Commented Jun 5, 2012 at 21:49
  • @C2H5OH It just yields a generic “syntax error”, as echo is not a keyword and it expects something else to happen after a possible variable name (for example an assignment). Commented Jun 5, 2012 at 21:51
  • @poke: Thanks, I already knew that. I was only trying to improve the OP's manners when asking questions. Commented Jun 5, 2012 at 21:54
  • @C2H5OH Already thought you did, but to be fair, “syntax error” is as exact as possible in this case ^^ Commented Jun 5, 2012 at 21:55

2 Answers 2

11

You cannot use UNIX commands in your Python script as if they were Python code, echo name is causing a syntax error because echo is not a built-in statement or function in Python. Instead, use print name.

To run UNIX commands you will need to create a subprocess that runs the command. The simplest way to do this is using os.system(), but the subprocess module is preferable.

Sign up to request clarification or add additional context in comments.

Comments

11

you can also use subprocess module.

import subprocess
proc = subprocess.Popen(['echo', name],
                            stdin = subprocess.PIPE,
                            stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE
                        )

(out, err) = proc.communicate()
print out

Read: http://www.doughellmann.com/PyMOTW/subprocess/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.