Converting from shell to python
__peter__ at web.de
Mon Feb 21 18:07:19 CET 2011
> I have been using shell for a "long" time and I decided to learn python
> recently. So far I am liking it a lot especially the argparse module which
> makes my programs more professional like.
> Currently, I am rewriting my bash scripts to python so I came across a
> subprocess and environment problem.
> My bash script looks like this,
> #!/usr/bin/env bash
> export JAVA_HOME="/opt/java"
> export PROG="dbconn"
> export JAVA_ARGS="-Xmx16g"
> export ARGS="-out outdata.dat"
> $JAVA_HOME $JAVA_ARGS $PROG $ARGS
> To convert this into python I did something like this (which isn't working
> #!/usr/bin/env python
> import subprocess,os
> def execute():
> cmd="$JAVA_HOME $JAVA_ARGS $PROG $ARGS"
Here you turn cmd into a list
and now you are wrapping it to [...], i. e. you get a list of list. Also, to
enable shell expansion you have to invoke Popen(..., shell=True).
> except OSError, e:
> print >>sys.stderr," Execution failed: ",e
> return p.stdout
> So, I was wondering if this is the correct way of doing it? or is there an
I think the easiest way is to avoid environment variables and use python
variables instead, e. g.
JAVA_HOME = "/opt/java"
JAVA_ARGS = "-Xmx16g"
cmd = [JAVA_HOME, JAVA_ARGS, ...]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
More information about the Python-list