I am a Python Novice so please help me out…
#!/usr/bin/python -tt
import sys
import commands
def runCommands():
f = open("a.txt", 'r')
for line in f: # goes through a text file line by line
cmd = 'ls -l ' + line
print "printing cmd = " + cmd,
(status, output) = commands.getstatusoutput(cmd)
if status: ## Error case, print the command's output to stderr and exit
print "error"
sys.stderr.write(output)
sys.exit(1)
print output
f.close()
def main():
runCommands()
# Standard boilerplate at end of file to call main() function.
if __name__ == '__main__':
main()
I run it as follows:
$python demo.py
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error
Running less $(which python) says:
#!/bin/sh bin=$(cd $(/usr/bin/dirname "$0") && pwd) exec -a "$0" "$bin/python2.5" "$@"
If i remove for loop then it works fine
$cat a.txt
dummyFile
$ls -l dummyFile
-rw-r--r-- 1 blah blah ...................
$python demo.py
printing cmd = ls -l dummyFile
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error
I am using ‘ls’ just for showing the problem. Actually i wanna use some internal shell scripts so i have to run this python script in this way only.
The problem is caused by this line:
it should be modified to:
When you read the line from your text file, you also read the trailing
\n. You need to strip this so that it works. Thegetstatusoutput()doesn’t like the trailing newline. See this interactive test (which is how I verified it):