2

I have a python script which invokes two different shell scripts. The first script sets some environment variables which are required by the second script. The python code has the following structure :

import subprocess
subprocess.call(["bash", "a.sh"]) #a.sh sets env_var1
subprocess.call(["bash", "b.sh"]) #b.sh reads env_var1

Because the scripts a.sh and b.sh run in different shells, the above code does not do the needful. I want to know that can we execute these shell scripts from python in the current shell itself

2

1 Answer 1

0

You can use this line to run commands to your shell in python os.system('command to run here')

In your case it would be something like:

import os

os.system('./a.sh')
os.system('./b.sh')
Sign up to request clarification or add additional context in comments.

9 Comments

but how do I run both scripts in one os.system
the os.system doesn't leave the current shell, so running the one after the other will ensure the environment variables are created in the first script and accessible in the second
yes out of python it works. Following is my python script path1 = r'd1/xyz.csh' path2 = r'd2/abc.csh' os.system("cat d1/xyz.csh") os.system(path1) os.system("echo $Env_var_1 sys1") os.system(path2). And xyz.csh is Env_var_1="var one by xyz" Env_var_2="var two by xyz" echo $Env_var_1. And abc.csh is echo $Env_var_2, "in abc"
use export when creating the variable
The issue is that os.system in fact does spawn a subprocess in which the subshell runs. It does so for every call to os.system which means you get a "fresh" process/subshell every time. Just try os.system("export MYVAR=someval; echo $MYVAR") and then os.system("echo $MYVAR"), or simply consecutive calls to os.system("echo $$").
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.