如何在 Linux 上使用 Python 导出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1506010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use export with Python on Linux
提问by Kevin Campion
I need to make an export like this in Python :
我需要在 Python 中进行这样的导出:
# export MY_DATA="my_export"
I've tried to do :
我试过这样做:
# -*- python-mode -*-
# -*- coding: utf-8 -*-
import os
os.system('export MY_DATA="my_export"')
But when I list export, "MY_DATA" not appear :
但是当我列出导出时,“MY_DATA”不会出现:
# export
How I can do an export with Python without saving "my_export" into a file ?
如何在不将“my_export”保存到文件中的情况下使用 Python 进行导出?
采纳答案by Alex
You actually want to do
你真的想做
import os
os.environ["MY_DATA"] = "my_export"
回答by Thomas Zoechling
You could try os.environ["MY_DATA"] instead.
你可以试试 os.environ["MY_DATA"] 代替。
回答by phoku
Not that simple:
没那么简单:
python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty
But:
但:
python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123
回答by alex tingle
export
is a command that you give directly to the shell (e.g. bash
), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.
export
是您直接提供给外壳程序的命令(例如bash
),以告诉它添加或修改其环境变量之一。您无法从子进程(例如 Python)更改 shell 的环境,这是不可能的。
Here's what's happening with you try os.system('export MY_DATA="my_export"')
...
这是发生在你身上的事情,试试os.system('export MY_DATA="my_export"')
...
/bin/bash process, command `python yourscript.py` forks python subprocess
|_
/usr/bin/python process, command `os.system()` forks /bin/sh subprocess
|_
/bin/sh process, command `export ...` changes local environment
When the bottom-most /bin/sh
subprocess finishes running your export ...
command, then it's discarded, along with the environment that you have just changed.
当最底层的/bin/sh
子进程完成运行您的export ...
命令时,它会与您刚刚更改的环境一起被丢弃。
回答by Jagadeswaran
os.system ('/home/user1/exportPath.ksh')
os.system ('/home/user1/exportPath.ksh')
exportPath.ksh:
导出路径.ksh:
export PATH=MY_DATA="my_export"
export PATH=MY_DATA="my_export"
回答by mikepk
Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.
执行此操作的另一种方法,如果您赶时间并且不介意 hacky 回味,则是在 bash 环境中执行 python 脚本的输出,并打印出执行在 python 中设置环境的命令。不理想,但它可以在紧要关头完成工作。它不是很容易跨壳移植,所以 YMMV。
$(python -c 'print "export MY_DATA=my_export"')
(you can also enclose the statement in backticks in some shells ``)
(您也可以在某些 shell 中用反引号将语句括起来``)
回答by Christopher Hunter
Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.
有点像 hack,因为它并不是真正的 python 在这里做任何特别的事情,但是如果你在同一个子 shell 中运行 export 命令,你可能会得到你想要的结果。
import os
cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
os.system(cmd)
回答by OriginalNewBee
In the hope of providing clarity over common cinfusion...
希望能澄清常见的输液...
I have written many python <--> bash <--> elfbin toolchains and the proper way to see it is such as this:
我写了很多 python <--> bash <--> elfbin 工具链,正确的查看方法是这样的:
Each process (originator) has a state of the environment inherited from whatever invoked it. Any change remains lokal to that process. Transfering an environment state is a function by itself and runs in two directions, each with it's own caveats. The most common thing is to modify environment before running a sub-process. To go down to the metal, look at the exec() - call in C. There is a variant that takes a pointer to environment data. This is the only actually supported transfer of environment in typical OS'es.
每个进程(发起者)都有一个从调用它的对象继承的环境状态。任何变化都与该过程有关。转移环境状态本身就是一个函数,它在两个方向上运行,每个方向都有自己的警告。最常见的是在运行子进程之前修改环境。要深入了解,请查看 C 中的 exec() 调用。有一个变体采用指向环境数据的指针。这是典型操作系统中唯一实际支持的环境传输。
Shell scripts will create a state to pass when running children when you do an export. Otherwise it just uses that which it got in the first place.
Shell 脚本将创建一个状态以在您执行export时运行子项时传递。否则它只会使用它最初得到的东西。
In all other cases it will be some generic mechanism used to pass a set of data to allow the calling process itself to update it's environment based on the result of the child-processes output.
在所有其他情况下,它将使用某种通用机制来传递一组数据,以允许调用进程本身根据子进程输出的结果更新其环境。
Ex:
前任:
ENVUPDATE = $(CMD_THAT_OUTPUTS_KEYVAL_LISTS)
echo $ENVUPDATE > $TMPFILE
source $TMPFILE
The same can of course be done using json, xml or other things as long as you have the tools to interpret and apply.
当然,同样可以使用 json、xml 或其他东西来完成,只要你有解释和应用的工具。
The need for this may be (50% chance) a sign of misconstruing the basic primitives and that you need a better config or parameter interchange in your solution.....
对此的需求可能(50% 的机会)是误解基本原语的迹象,并且您需要在解决方案中进行更好的配置或参数交换.....
Oh, in python I would do something like... (need improvement depending on your situation)
哦,在 python 中,我会做类似的事情......(根据你的情况需要改进)
import re
RE_KV=re.compile('([a-z][\w]*)\s*=\s*(.*)')
OUTPUT=RunSomething(...) (Assuming 'k1=v1 k2=v2')
for kv in OUTPUT.split(' ')
try:
k,v=RE_KV.match(kv).groups()
os.environ[k]=str(v)
except:
#The not a property case...
pass
回答by Alechan
One line solution:
一行解决方案:
eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`
echo $python_include_path # prints /home/<usr>/anaconda3/include/python3.6m" in my case
Breakdown:
分解:
Python call
Python 调用
python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'
It's launching a python script that
它正在启动一个 python 脚本
- imports sysconfig
- gets the python include path corresponding to this python binary (use "which python" to see which one is being used)
- prints the script "python_include_path={0}" with {0} being the path from 2
- 导入系统配置
- 获取与此python二进制文件对应的python包含路径(使用“which python”查看正在使用的是哪个)
- 打印脚本“python_include_path={0}”,其中 {0} 是 2 的路径
Eval call
评估电话
eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`
It's executing in the current bash instance the output from the python script. In my case, its executing:
它在当前 bash 实例中执行 python 脚本的输出。在我的情况下,它的执行:
python_include_path=/home/<usr>/anaconda3/include/python3.6m
In other words, it's setting the environment variable "python_include_path" with that path for this shell instance.
换句话说,它正在使用此 shell 实例的路径设置环境变量“python_include_path”。
Inspired by: http://blog.tintoy.io/2017/06/exporting-environment-variables-from-python-to-bash/
灵感来自:http: //blog.tintoy.io/2017/06/exporting-environment-variables-from-python-to-bash/
回答by Akhil Soni
I have an excellent answer.
我有一个很好的答案。
#! /bin/bash
output=$(git diff origin/master..origin/develop | \
python -c '
# DO YOUR HACKING
variable1_to_be_exported="Yo Yo"
variable2_to_be_exported="Honey Singh"
… so on
magic=""
magic+="export onShell-var1=\""+str(variable1_to_be_exported)+"\"\n"
magic+="export onShell-var2=\""+str(variable2_to_be_exported)+"\""
print magic
'
)
eval "$output"
echo "$onShell-var1" // Output will be Yo Yo
echo "$onShell-var2" // Output will be Honey Singh
Mr Alex Tingle is correct about those processes and sub-process stuffs
Alex Tingle 先生关于这些流程和子流程的内容是正确的
How it can be achieved is like the above I have mentioned. Key Concept is :
如何实现就像我上面提到的那样。关键概念是:
- Whatever
printed
from python will be stored in the variable in the catching variable inbash
[output
] - We can execute any command in the form of string using
eval
- So, prepare your
print
output from python in a meaningfulbash
commands - use
eval
to execute it in bash
- 无论
printed
从蟒将被存储在变量中的捕捉变量bash
[output
] - 我们可以使用字符串形式执行任何命令
eval
- 因此,
print
在有意义的bash
命令中准备来自 python的输出 - 用于
eval
在 bash 中执行它
And you can see your results
你可以看到你的结果
NOTEAlways execute the eval
using double quotes
or else bash
will mess up your \n
s and outputs will be strange
注意总是执行eval
usingdouble quotes
否则bash
会弄乱你的\n
s 并且输出会很奇怪
PS: I don't like bash but your have to use it
PS:我不喜欢 bash 但你必须使用它