从bash脚本访问python字典 [英] accessing python dictionary from bash script
问题描述
我正在从python脚本调用bash脚本.
I am invoking the bash script from python script.
我希望bash脚本在python脚本中向字典"d"中添加一个元素
I want the bash script to add an element to dictionary "d" in the python script
#!/bin/bash
rank=1
echo "plugin"
function reg()
{
if [ "$1" == "what" ]; then
python -c 'from framework import data;data(rank)'
echo "iamin"
else
plugin
fi
}
plugin()
{
echo "i am plugin one"
}
reg $1
python文件:
import sys,os,subprocess
from collections import *
subprocess.call(["./abc3.sh what"],shell=True,executable='/bin/bash')
def data(rank,check):
d[rank]["CHECK"]=check
print d[1]["CHECK"]
推荐答案
让我们假设您有一个回显值的shell插件:
Let's suppose that you have a shell plugin that echoes the value:
echo $1 12
样机python脚本看起来像(我在Windows/MSYS2 BTW上,因此对于Linux用户来说是奇怪的路径):
The mockup python script looks like (I'm on windows/MSYS2 BTW, hence the strange paths for a Linux user):
import subprocess
p = subprocess.Popen(args=[r'C:\msys64\usr\bin\sh.exe',"-c","C:/users/jotd/myplugin.sh myarg"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
o,e= p.communicate()
p.wait()
if len(e):
print("Warning: error found: "+e.decode())
result = o.strip()
d=dict()
d["TEST"] = result
print(d)
它打印字典,证明参数已传递到外壳程序,并返回处理.请注意,stderr已被过滤掉,以避免与结果混淆,但如果发生,则会打印到控制台.
it prints the dictionary, proving that argument has been passed to the shell, and went back processed. Note that stderr has been filtered out to avoid been mixed up with the results, but is printed to the console if occurs.
{'TEST': b'myarg 12'}
这篇关于从bash脚本访问python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!