2

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

arsenal
  • 23,366
  • 85
  • 225
  • 331
  • Encoding it probably the best way. Find a encoding that works equal between Python and Bash :) –  Dec 24 '13 at 21:00

1 Answers1

3

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)

Community
  • 1
  • 1
cptPH
  • 2,401
  • 1
  • 29
  • 35
  • Can you please provide an example basis on my scenario? I tried doing this in the way but it doesn't work for me.. Take a look in jsonStr document it is not in the format in which you have declared foo variable.. – arsenal Dec 24 '13 at 21:05
  • Thanks.. Yeah there is an error.. `os.putenv('jj', ' '.join(jj['pp'])) TypeError: sequence item 0: expected string, int found` Not sure how to fix it.. I know its a pretty simple problem I guess but this is my third day with Python so lot of things are little bit rusty to me.. Any idea how to fix this? – arsenal Dec 24 '13 at 21:16
  • ok updated with input from this: http://stackoverflow.com/questions/10880813/typeerror-sequence-item-0-expected-string-int-found, join needs the elements to be strings ;-) – cptPH Dec 24 '13 at 21:23