Simon
Simon

Reputation: 83

Execute python code from within a shell script

I want to have some python code run within a shell script. I don't want to rely on an external file to be ran. Is there any way to do that?

I did a ton of googling, but there aren't any clear answers. This code is what I find... But it relies on the external python script to be ran. I want it all within one file.

python python_script.py

Upvotes: 1

Views: 292

Answers (2)

Roland Smith
Roland Smith

Reputation: 43495

You can use a so-called "here document":

#!/usr/bin/env bash

echo "hello from bash"

python3 - <<'EOF'
print("hello from Python 3")
EOF

The single quotes around the first EOF prevent the usual expansions and command substitions in a shell script.

If you want those to happen, simply remove them.

Upvotes: 3

santamanno
santamanno

Reputation: 636

If you mean within a BASH shell script without executing any external dependencies, I am afraid you're out of luck, since BASH only interprets its own scripting language.

Your question is somewhat like asking "Can I run a Java .class file without the JVM"? Obviously, you will always have the external dependency of the JRE/JVM. This is the same case, you depend on the external Python compiler and interpreter.

Optionally, you have the option of including the python script inline, but it would still require the python executable.

This works:

python -c 'print("Hi")'

Or this with BASH redirection:

python <<< 'print("Hi")'

Upvotes: 1

Related Questions