I want to call scripts from a directory (they are executable shell scripts) via python.
so far so good:
for script in sorted(os.listdir(initdir), reverse=reverse):
if script.endswith('.*~') or script == 'README':
continue
if os.access(script, os.X_OK):
try:
execute = os.path.abspath(script)
sp.Popen((execute, 'stop' if reverse else 'start'),
stdin=None, stderr=sp.PIPE,
stdout=sp.stderr, shell=True).communicate()
except:
raise
Now what i Want is: lets say i have a bash script with a start functiont. from which I call
echo “Something”
Now I want to see that echo on sys.stdout and the exit Code. I believe you do this with .communicate() but mine doesn’t work the way i thought it would.
What am I doing wrong?
Any help is much appreciated
Confer http://docs.python.org/library/subprocess.html.
After the subprocess has finished, you can get the return code from the Popen instance:
Likewise, you can achieve your goals like that:
By the way, I would change the test
into a positive one:
It is better to be explicit about what you would like to execute than being explicit about what you do not want to execute.
Also, you should name your variables in a more general fashion, so
scriptshould befilenamein the first place. Aslistdiralso lists directories, you can explicitly check for those. Your currenttry/exceptblock is not proper as long as you do not handle a specific exception. Instead ofabspath, you should just concatenateinitdirandfilename, which is a concept often applied in context ofos.listdir(). For security reasons, useshell=Truein the constructor of thePopenobject only if you are absolutely sure that you require it. Let me suggest the following: