简体   繁体   中英

How to run a shell script as source using python to set environment variables?

I created a shell script which is used to set the environment variables. I am trying to run this script via a python script but every time shows me error as "Command not found". I want to run the shell script as source for setting up the environment variables.

Python : 2.7.5
Script Name : abc.sh
Normal Execution on shell : source abc.sh

Tried using

python : os.system ("source abc.sh") 

this shows an error as

"Command not found".

Anybody can help me out how to run this script successfully as source via python?

The error is because source is a shell "builtin" command -- it is not an external command in your $PATH. But the more fundamental problem is that what you're trying to do won't work due to how environment variables work.

Env vars are private to each process. They are not global and a process cannot modify the env vars of a different process; at least not without the cooperation of the other process. When you start a process it inherits a copy of the env vars of the parent process or the parent provides an explicit set of env vars to the child process it spawns. In either event each process has its own, private, env vars. So even if you did

os.system("sh -c 'source abc.sh'")

it would only modify the env vars of the sh subprocess. It would not modify the environment of the python process.

The simplest solution is to start a shell, do the source abc.sh , then exec your python program. If you absolutely have to set the env vars by running a shell script from within your python program your script will have to write the vars to stdout. Your python program will then have to read that output and parse it to extract the env vars names and value then call os.putenv() to set each var in the python process.

Try your command in command prompt. This because you have not define os in the your command python: os.system ("source abc.sh"). Your computer is unable access os.system. You first need to install the packages of python which os.system module in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM