如何将Python数组作为数组传递给shell脚本?

时间:2021-12-13 07:13:22

I have a shell script (test.sh) in which I am using bash arrays like this -

我有一个shell脚本(test.sh),在其中我使用了这样的bash数组

#!/bin/bash

...

echo $1
echo $2

PARTITION=(0 3 5 7 9)

for el in "${PARTITION[@]}"
do
    echo "$el"
done

...

As of now, I have hardcoded the values of PARTITION array in my shell script as you can see above..

到目前为止,我已经在shell脚本中硬编码了分区数组的值。

Now I have a Python script as mentioned below from which I am calling test.sh shell script by passing certain parameters such as hello1 and hello2 which I am able to receive as $1 and $2. Now how do I pass jj['pp'] and jj['sp'] from my Python script to Shell script and then iterate over that array as I am doing currently in my bash script?

现在我有了下面提到的一个Python脚本,我从它调用test。sh shell脚本通过传递某些参数,如hello1和hello2,我可以接收到$1和$2。现在,如何将jj['pp']和jj['sp']从Python脚本传递到Shell脚本,然后像我当前在bash脚本中所做的那样对数组进行迭代呢?

Below script doesn't work if I am passing jj['pp']

如果我通过了jj['pp'],下面的脚本就不起作用了

import subprocess
import json
import os

hello1 = "Hello World 1"
hello2 = "Hello World 2"

jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
jj = json.loads(jsonData)

print jj['pp']
print jj['sp']

# foo = (0, 3, 5, 7, 9)

# os.putenv('FOO', ' '.join(foo))

print "start"
subprocess.call(['./test.sh', hello1, hello2, jj['pp']])
print "end"

UPDATE:-

更新:

Below JSON document is going to be in this format only -

下面的JSON文档将只采用这种格式-

jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'

so somehow I need to convert this to bash arrays while passing to shell script..

因此,我需要在传递到shell脚本时将其转换为bash数组。

1 个解决方案

#1


3  

Python

Python

import os
import json
import subprocess

hello1 = "Hello World 1"
hello2 = "Hello World 2"

jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
jj = json.loads(jsonData)

print jj['pp']
print jj['sp']

os.putenv( 'jj', ' '.join( str(v) for v in jj['pp']  ) )

print "start"
subprocess.call(['./test.sh', hello1, hello2 ])
print "end"

bash

bash

echo $1
echo $2

for el in $jj
do
    echo "$el"
done

Taken from here: Passing python array to bash script (and passing bash variable to python function)

从这里开始:将python数组传递给bash脚本(并将bash变量传递给python函数)

#1


3  

Python

Python

import os
import json
import subprocess

hello1 = "Hello World 1"
hello2 = "Hello World 2"

jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
jj = json.loads(jsonData)

print jj['pp']
print jj['sp']

os.putenv( 'jj', ' '.join( str(v) for v in jj['pp']  ) )

print "start"
subprocess.call(['./test.sh', hello1, hello2 ])
print "end"

bash

bash

echo $1
echo $2

for el in $jj
do
    echo "$el"
done

Taken from here: Passing python array to bash script (and passing bash variable to python function)

从这里开始:将python数组传递给bash脚本(并将bash变量传递给python函数)