简体   繁体   English

运行影响父 shell 的 Python 脚本(更改环境变量、运行其他脚本等)

[英]Run Python script that affect parent shell (changes environment variables, runs other scripts, etc.)

Recently I need to affect bash shell that runs python script from python script itseft.最近我需要影响从 python script iteft 运行 python 脚本的 bash shell。 I develop a Python utility package that add some additional functionallity to pip .我开发了一个Python 实用程序包,它为pip添加了一些额外的功能。 One of the workflows in this package needs to active Virtualenv to work as planned.此包中的工作流之一需要激活 Virtualenv 才能按计划工作。 Here is the problem.这是问题所在。

When you run something like:当你运行类似的东西时:

os.system('/bin/bash ./venv/bin/activate')

Or:或者:

subprocess.Popen(['/bin/bash', './venv/bin/activate')

It doesn't do anything to the shell when the script is executed.执行脚本时,它不会对 shell 做任何事情。 Basically because these commands are executed in isolated processes (I guess) and therefore does not affect bash process itself.基本上是因为这些命令是在隔离进程中执行的(我猜),因此不会影响 bash 进程本身。

Question: how can you affect parent shell that execute python script from inside the script (add some environments, run other script, etc.)?问题:如何影响从脚本内部执行 python 脚本的父 shell(添加一些环境,运行其他脚本等)?

Thanks in advance.提前致谢。

how can you affect parent shell that execute python script from inside the script (add some environments, run other script, etc.)?如何影响从脚本内部执行 python 脚本的父 shell(添加一些环境,运行其他脚本等)?

It is not possible to do that, unless your operating system is broken.这是不可能的,除非你的操作系统坏了。 Process isolation is one of the very basic concepts of an operating system.进程隔离是操作系统的基本概念之一。

Instead, resaerch what venv does and how it works and what activate script does and just add the proper directory to python module search path.相反,研究venv的作用及其工作原理以及activate脚本的作用,然后将正确的目录添加到 python 模块搜索路径。

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

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