Evan
Evan

Reputation: 479

Executing string of python code within bash script

I've come across a situation where it would be convenient to use python within a bash script I'm writing. I call some executables within my script, then want to do a bit of light data processing with python, then carry on. It doesn't seem worth it to me to write a dedicated script for the processing.

So what I want to do is something like the following:

# do some stuff in bash script
# write some data into datafile.d

python_fragment= << EOF
f = open("datafile.d")
// do some stuff with opened file
print(result)
EOF

result=$(execute_python_fragment $python_fragment) # <- what I want to do

# do some stuff with result

Basically all I want to do is execute a string containing python code. I could of course just make another file containing the python code and execute that, but I'd prefer not to do so. I could do something like echo $python_fragment > temp_code_file, then execute temp_code_file, but that seems inelegant. I just want to execute the string directly, if that's possible.

What I want to do seems simple enough, but haven't figured it out or found the solution online.

Thanks!

Upvotes: 3

Views: 8099

Answers (4)

Alex028502
Alex028502

Reputation: 3824

maybe something like

result=$(echo $python_fragment | python3)

only problem is the heredoc assignment in the question doesn't work either. But https://stackoverflow.com/a/1167849 suggests a way to do it if that is what you want to do:

python_fragment=$(cat <<EOF
print('test message')
EOF
) ;

result=$(echo $python_fragment | python3)

echo result was $result

Upvotes: 0

Simon Black
Simon Black

Reputation: 923

You can run a python command direct from the command line with -c option

python -c 'from foo import hello; print (hello())'

Then with bash you could do something like

result=$(python -c '$python_fragment')

Upvotes: 5

Poshi
Poshi

Reputation: 5762

You only have to redirect that here-string/document to python

python <<< "print('Hello')"

or

python <<EOF
print('Hello')
EOF

and encapsulate that in a function

execute_python_fragment() {
    python <<< "$1"
}

and now you can do your

result=$(execute_python_fragment "${python_fragment}")

You should also add some kind of error control, input sanitizing... it's up to you the level of security you need in this function.

Upvotes: 2

Emma H
Emma H

Reputation: 68

If the string contains the exact python code, then this simple eval() function works.

Here's a really basic example:

>>> eval("print(2)")
2

Hope that helps.

Upvotes: 0

Related Questions