1

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
Simon
  • 83
  • 1
  • 9
  • If I understand your question correctly, you mean like this?: https://stackoverflow.com/questions/3987041/run-function-from-the-command-line – walnut Aug 24 '19 at 21:36
  • c:\python27\python.exe c:\somescript.py %* https://stackoverflow.com/questions/4571244/creating-a-bat-file-for-python-script – PySeeker Aug 24 '19 at 22:58
  • Depends on your operating system & shell. Please tag your question accordingly. – martineau Aug 24 '19 at 23:20

2 Answers2

3

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.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
1

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")'
santamanno
  • 626
  • 4
  • 12