0

I have a shell script with first.sh and it calls a python script second.py internally.While this python script executes it sets some variable var=‘yes’ based on certain parameters.

now i need to pass this var variable to shell script which it is calling and do some processing . Please let me know how to do such.

I tried os.system(‘bash’) ,but its creating new session and the execution of the shell script is not continuing.

Core work
  • 3
  • 3

1 Answers1

0

A common pattern for this is to use file descriptors between the parent process (bash) and the child (python). In the simple case, just using standard input/output. So bash could read the result. Something like this:

#!/bin/bash
foo=$(python script.py)
echo "$foo"

If you need something more complex than a single variable, you will need to decide on some formatting for the data and how to process it (maybe output in json?)

slushpupie
  • 267
  • 2
  • 10
  • `$( ... )` [should be used in place of backticks](https://wiki.bash-hackers.org/scripting/obsolete), all-caps names are [defined by POSIX to be used for variables that modify shell or OS behavior](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html) and parameter expansions should *always* be in double quotes, even when passing to `echo` -- see [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo). – Charles Duffy Jan 28 '20 at 15:50
  • Good callout. This was a quick hack of an example. Will update. – slushpupie Jan 28 '20 at 15:52
  • But what if i have more the one variable in the python program,can this be taken care ? – Core work Jan 28 '20 at 16:11
  • @Corework, lots of possible ways to do that already elsewhere in our knowledgebase. Personally, I suggest duplicating the format of `/proc/self/environ` -- using NUL-delimited `key=value` pairs -- and using a [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001)-style loop to read them out and assign to an associative array. – Charles Duffy Jan 28 '20 at 17:12
  • If you have `jq` installed, you could output in json format and use `jq` to parse out the things you care about. But as @CharlesDuffy pointed out, there is a lot of ways to do this (data marshaling) and is going to depend a lot on the type of data you are passing, and what tools you have. – slushpupie Jan 28 '20 at 20:15