Python: Persistent shell variables in subprocess(Python:子进程中的持久外壳变量)
问题描述
我正在尝试使用 Python 的 subprocess 模块执行一系列命令,但是我需要在运行它们之前使用 export 设置 shell 变量.当然,shell 似乎不是持久的,所以当我稍后运行命令时,这些 shell 变量会丢失.
I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.
有没有办法解决这个问题?我可以创建一个/bin/sh 进程,但是如何获得在该进程下运行的命令的退出代码?
Is there any way to go about this? I could create a /bin/sh process, but how would I get the exit codes of the commands run under that?
推荐答案
subprocess.Popen
采用一个可选的命名参数 env
,它是用作子进程环境的字典(你所描述的shell变量").根据需要准备一个字典(您可以从 os.environ
的副本开始并根据需要进行更改)并将其传递给所有 subprocess.Popen
调用您执行.
subprocess.Popen
takes an optional named argument env
that's a dictionary to use as the subprocess's environment (what you're describing as "shell variables"). Prepare a dict as you need it (you may start with a copy of os.environ
and alter that as you need) and pass it to all the subprocess.Popen
calls you perform.
这篇关于Python:子进程中的持久外壳变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:子进程中的持久外壳变量


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01