问题
#!/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.
回答1:
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.
回答2:
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/
来源:https://stackoverflow.com/questions/10905427/how-to-execute-a-unix-command-in-python-script