bash 从python脚本设置bash变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26767552/
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
set bash variable from python script
提问by Melodie Gauthier
i'm calling a python script inside my bash script and I was wondering if there is a simple way to set my bash variables within my python script.
我正在我的 bash 脚本中调用一个 python 脚本,我想知道是否有一种简单的方法可以在我的 python 脚本中设置我的 bash 变量。
Example:
例子:
My bash script:
我的 bash 脚本:
#!/bin/bash
someVar=""
python3 /some/folder/pythonScript.py
My python script:
我的python脚本:
anotherVar="HelloWorld"
Is there a way I can set my someVar to the value of anotherVar? I was thinking of printing properties in a file inside the python script and then read them from my bash script but maybe there is another way. Also I don't know and don't think it makes any difference but I can name both variable with the same name (someVar/someVar instead of someVar/anotherVar)
有没有办法可以将我的 someVar 设置为 anotherVar 的值?我正在考虑在 python 脚本内的文件中打印属性,然后从我的 bash 脚本中读取它们,但也许还有另一种方法。此外,我不知道也不认为这有什么区别,但我可以用相同的名称命名这两个变量(someVar/someVar 而不是 someVar/anotherVar)
回答by Martin Tournoij
No, when you execute python
, you start a new process, and every process has access onlyto their own memory. Imagine what would happen if a process could influence another processes memory! Even for parent/child processes like this, this would be a huge security problem.
不,当您执行时python
,您启动了一个新进程,并且每个进程只能访问自己的内存。想象一下,如果一个进程可以影响另一个进程的内存会发生什么!即使对于这样的父/子进程,这也将是一个巨大的安全问题。
You can make python print()
something and use that, though:
不过,您可以制作 pythonprint()
并使用它:
#!/usr/bin/env python3
print('Hello!')
And in your shell script:
在你的 shell 脚本中:
#!/usr/bin/env bash
someVar=$(python3 myscript.py)
echo "$someVar"
There are, of course, many others IPC techniques you could use, such as sockets, pipes, shared memory, etc... But without context, it's difficult to make a specific recommendation.
当然,您还可以使用许多其他 IPC 技术,例如套接字、管道、共享内存等……但是如果没有上下文,就很难提出具体建议。
回答by Charles Duffy
shlex.quote()
in Python 3, or pipes.quote()
in Python 2, can be used to generate code which can be eval
ed by the calling shell. Thus, if the following script:
shlex.quote()
在 Python 3 或pipes.quote()
Python 2 中,可用于生成eval
可由调用 shell 编辑的代码。因此,如果以下脚本:
#!/usr/bin/env python3
import sys, shlex
print('export foobar=%s' % (shlex.quote(sys.argv[1].upper())))
...is named setFoobar
and invoked as:
...被命名setFoobar
和调用为:
eval "$(setFoobar argOne)"
...then the calling shell will have an environment variable set with the name foobar
and the value argOne
.
...然后调用 shell 将有一个环境变量,设置为 namefoobar
和 value argOne
。