Hemant
Hemant

Reputation: 1343

How can I find out if os.popen is running the linux command in same shell?

I've the below python function that I use to run the linux command. I'm running a script which creates some environment variable and then I'm porting all those variable into on script again by running the linux command using the function below; however it seems that the environment variables of the first command is not getting recorded using second command. I was wondering is it because the os.popen runs command in different shell every time I call it? If so how can I modify my code or which function to use to have everything running in the same shell?

def execute(cmd):
    '''Module to execute linux command'''
    try:
        proc = os.popen(cmd)
        out = proc.read().strip()
        return out
    except Exception,err:
        print "Exception occurred : %s"%str(err)
        raise(str(err))

Upvotes: 0

Views: 217

Answers (2)

popen(3) (and in Python os.popen) never runs the same shell, but forks a new one.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249502

os.popen() is deprecated. In its place we have subprocess.Popen() and perhaps even better for your use case, subprocess.check_output(). These new methods take an optional env argument which is a dict of environment variable names and values. You can pass anything you need in there.

Or, if you really want to set the variables outside and have them "stick" in subprocesses, you can export them in the shell (export myvarname) before running Python.

Upvotes: 1

Related Questions