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.

DSM
  • 342,061
  • 65
  • 592
  • 494
user1204195
  • 493
  • 5
  • 12
  • 19
  • 3
    You should at least specify the exact error message you're obtaining. – C2H5OH Jun 05 '12 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? – poke Jun 05 '12 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). – poke Jun 05 '12 at 21:51
  • @poke: Thanks, I already knew that. I was only trying to improve the OP's manners when asking questions. – C2H5OH Jun 05 '12 at 21:54
  • @C2H5OH Already thought you did, but to be fair, *“syntax error”* is as exact as possible in this case ^^ – poke Jun 05 '12 at 21:55

2 Answers2

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
10

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/

pyfunc
  • 65,343
  • 15
  • 148
  • 136