简体   繁体   English

如何使用 python 将 shell 脚本作为源运行以设置环境变量?

[英]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.我创建了一个 shell 脚本,用于设置环境变量。 I am trying to run this script via a python script but every time shows me error as "Command not found".我正在尝试通过 python 脚本运行此脚本,但每次都显示错误为“找不到命令”。 I want to run the shell script as source for setting up the environment variables.我想运行 shell 脚本作为设置环境变量的源。

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?任何人都可以帮助我如何通过 python 成功运行此脚本作为源代码?

The error is because source is a shell "builtin" command -- it is not an external command in your $PATH.错误是因为source是 shell“内置”命令——它不是 $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.它只会修改sh子进程的环境变量。 It would not modify the environment of the python process.它不会修改 python 进程的环境。

The simplest solution is to start a shell, do the source abc.sh , then exec your python program.最简单的解决方案是启动 shell,执行source abc.sh ,然后exec您的 python 程序。 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.如果您绝对必须通过在 python 程序中运行 shell 脚本来设置环境变量,则您的脚本必须将变量写入标准输出。 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.然后,您的 python 程序将必须读取 output 并对其进行解析以提取环境变量名称和值,然后调用os.putenv()在 python 进程中设置每个变量。

Try your command in command prompt.在命令提示符下尝试您的命令。 This because you have not define os in the your command python: os.system ("source abc.sh").这是因为您没有在命令 python: os.system ("source abc.sh") 中定义 os。 Your computer is unable access os.system.您的计算机无法访问 os.system。 You first need to install the packages of python which os.system module in it.您首先需要安装其中 os.system 模块的 python 的软件包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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