Converting from shell to python

Peter Otten __peter__ at
Mon Feb 21 18:07:19 CET 2011

Rita wrote:

> Hello,
> 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"
> To convert this into python I did something like this (which isn't working
> properly)
> #!/usr/bin/env python
> import subprocess,os
> def execute():
>   try:
>     cmd=cmd.split()

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).

> outdata.dat"},
>          stdout=subprocess.PIPE)
>   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
> alternative?

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 mailing list