1

Currently, I have following code works:

a.sh

echo "start"

export abc="hello"
a=`python a.py`
echo $a

echo "end"

a.py

import os
print os.getenv('abc')*2

Above, my shell script need one python script' help to handle something then back the answer to shell script.

Although it works, we need to write another python file, the requirement is to afford single file to users, so how it makes, I remember I have once saw some kind of realize which combine shell and python code, could anyone also know that & give me some clue?

atline
  • 28,355
  • 16
  • 77
  • 113
  • Why not write everything in python? – syntonym Feb 10 '18 at 12:29
  • backticks aren't recommended, by the way, `$( cmd )` is. Its easier for nesting etc. – Guy Feb 10 '18 at 12:38
  • @backticks, why backticks not recommended? – atline Feb 10 '18 at 12:53
  • @syntonym, this is just an example, in real scenario, we have most of our thing written in bash already, and just a little code need to be written in python for some reasons. – atline Feb 10 '18 at 12:56
  • 1
    It's the same character to start and end makes them more difficult to use correctly. The way I suggested does the same thing, but with less escaping issues. https://stackoverflow.com/q/9405478 – Guy Feb 10 '18 at 13:03
  • 1
    @Guy, i knew both of them, but did not realize the difference between them, really a windfall, thanks. – atline Feb 10 '18 at 13:08

2 Answers2

5

You could use python's -c option in your a.sh file:

echo "start"

export abc="hello"
a=$(python -c "import os ; print os.getenv('abc') * 2")
echo $a

echo "end"
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
2

a.sh

echo "start"

export abc="hello"
a=`python <<- EOF
import os
print os.getenv('abc')*2
EOF`
echo $a

echo "end"
atline
  • 28,355
  • 16
  • 77
  • 113