3

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

1
  • Encoding it probably the best way. Find a encoding that works equal between Python and Bash :) Commented Dec 24, 2013 at 21:00

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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..
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?
ok updated with input from this: stackoverflow.com/questions/10880813/…, join needs the elements to be strings ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.