从python脚本设置bash变量 [英] set bash variable from python script
问题描述
我正在bash脚本中调用一个python脚本,我想知道是否有一种简单的方法可以在我的python脚本中设置bash变量.
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脚本:
#!/bin/bash
someVar=""
python3 /some/folder/pythonScript.py
我的python脚本:
My python script:
anotherVar="HelloWorld"
是否可以将someVar设置为anotherVar的值?我当时想在python脚本中的文件中打印属性,然后从我的bash脚本中读取它们,但是也许还有另一种方法.我也不知道,也不认为这有什么区别,但是我可以用相同的名称(someVar/someVar而不是someVar/anotherVar)来命名两个变量.
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)
推荐答案
不,当您执行python
时,您将启动一个新进程,并且每个进程只能对其自己的内存进行 访问.想象一下,如果一个进程可能影响另一个进程的内存,将会发生什么!即使对于这样的父/子进程,这也将是一个巨大的安全问题.
No, when you execute python
, you start a new process, and every process has access only to 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 print()
并使用它,
You can make python print()
something and use that, though:
#!/usr/bin/env python3
print('Hello!')
在您的shell脚本中:
And in your shell script:
#!/usr/bin/env bash
someVar=$(python3 myscript.py)
echo "$someVar"
当然,您可以使用许多其他IPC技术,例如套接字,管道,共享内存等.但是如果没有上下文,很难提出具体的建议.
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.
这篇关于从python脚本设置bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!