Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass Python arrays to shell script as an Array?

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

#!/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..

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?

Below script doesn't work if I am passing 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 -

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..

like image 803
arsenal Avatar asked Apr 08 '26 06:04

arsenal


1 Answers

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

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)

like image 157
cptPH Avatar answered Apr 10 '26 02:04

cptPH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!