将变量从Python传递到Bash [英] Pass variable from Python to Bash

查看:46
本文介绍了将变量从Python传递到Bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个bash脚本,其中嵌入了一个小的python脚本.我想将变量从python传递到bash.经过几次搜索后,我仅找到基于 os.environ 的方法.

I am writing a bash script in which a small python script is embedded. I want to pass a variable from python to bash. After a few search I only found method based on os.environ.

我只是无法使其工作.这是我的简单测试.

I just cannot make it work. Here is my simple test.

#!/bin/bash

export myvar='first'

python - <<EOF
import os
os.environ["myvar"] = "second"
EOF

echo $myvar

我希望它输出 second ,但是仍然输出 first .我的脚本出了什么问题?还可以在没有 export 的情况下传递变量吗?

I expected it to output second, however it still outputs first. What is wrong with my script? Also is there any way to pass variable without export?

摘要

感谢所有答案.这是我的总结.

Thanks for all answers. Here is my summary.

嵌入在bash中的python脚本将作为子进程运行,根据定义,它不会影响父bash环境.

A python script embedded inside bash will run as child process which by definition is not able to affect parent bash environment.

解决方案是将分配字符串从python中传递出去,然后 eval 将其传递给bash.

The solution is to pass assignment strings out from python and eval it subsequently in bash.

一个例子是

#!/bin/bash
a=0
b=0

assignment_string=$(python -<<EOF
var1=1
var2=2
print('a={};b={}'.format(var1,var2))
EOF
)

eval $assignment_string

echo $a
echo $b

推荐答案

  1. 除非使用 Python 对原始数据进行某种操作,否则无需导入任何内容.答案可能很la脚:

  1. Unless Python is used to do some kind of operation on the original data, there's no need to import anything. The answer could be as lame as:

myvar=$(python - <<< "print 'second'") ; echo $myvar

  • 假设出于某种原因需要使用 Python 来吐出一堆 bash 变量和赋值,或者(谨慎地)即时编写代码. eval 方法:

  • Suppose for some reason Python is needed to spit out a bunch of bash variables and assignments, or (cautiously) compose code on-the-fly. An eval method:

    myvar=first
    eval $(python - <<< "print('myvar=second')" )
    echo $myvar
    

  • 这篇关于将变量从Python传递到Bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆