1

The .sh script contains all the paths and variables which I might need in my python script. I do not want to create a .py file and export it in my program as that will require lot of changes. I tried using subprocess module but not sure how to get the variables for using in py script. Is there any way or I will ultimately have to import a new .py file containing all declarations.

Thanks in advance.

1 Answers1

0

You're trying to set environment variables from within the python program, that are set in a shell script. I don't think it's possible in any straightforward way. However, you could set up a jacket for your python program that sources the shell script before calling the python program. Then the Python program can access the environment variables as os.environ, for example:

import os
print(os.environ['HOME'])

The reason it's not possible in a straightforward way is that subprocess (or any other means to run the shell script) will execute the shell script in a new process, and environment variable settings will be discarded when that process exits.

Another way would be to write another shell script that prints the names and values of all the shell values you need. In your python program, use subprocess to source both the original script and then your add-on script, and then parse the output to extract the variable names and values. The trickiest part here is handling special characters in values.

Jeff Learman
  • 2,506
  • 1
  • 18
  • 28
  • Thanks a lot Jeff....the jacket is more feasible for me than handling special symbols. It's working completely fine for me. – Saurabh Pandey Apr 23 '18 at 21:00
  • Welcome to StackOverflow. When you find an answer acceptable, the best way to show thanks is to accept the answer, which also shows to folks looking for questions to answer that this one has been. – Jeff Learman Apr 23 '18 at 22:30