Loading...
X

How to run small Python code in Bash

Bash is not only and even not so much shell built-in functions as command line programs (utilities). By running these commands and transferring the received data to the pipeline (through the pipe), you can automate a variety of things, programming of which in other programming languages can take a lot of effort.

This post will show you how to run Python code in Bash, and how to run a Python program in a Bash script.

How to execute Python code in Bash

On the Bash command line, use the following construct to execute code:

python -c "CODE"

For instance:

python -c "print (\"It works\")"

Another option that may come in handy in more exotic circumstances:

bash -c 'python -c "print (\"CODE\")"'

For instance:

bash -c 'python -c "print (\"It works\")"'

How to run a Python program in a Bash script

To execute a Python program in a Bash script, use a command like:

python SCRIPT.py ARGUMENT1 ARGUMENT2 ARGUMENT3

An example of running the extractor.py script passing two arguments: the value of the $line variable and 8080:

python extractor.py $line 8080

How to run a Python program in a Bash script and assign its output to a variable

If you need to run a Python script, and then assign the program output to a Bash variable, then use a construction like this:

ПЕРЕМЕННАЯ=`python SCRIPT.py ARGUMENT1 ARGUMENT2 ARGUMENT3`

Example:

response=`python extractor.py $line 8080 2>/dev/null | sed -E "s/\/\/.+:/\/\/$line:/"`

How to embed Python code into a Bash script

If Python code cannot be used on one line and you do not want to use an external script to call, then the following construction will work for you:

#!/bin/bash

script=`cat <<_EOF_
CODE
_EOF_`

echo "$script" | python

Where the CODE is, paste the Python code.

This example is working:

#!/bin/bash

value="I will be in the script!"

script=`cat <<_EOF_
print ("It works")
print ("Line 2")
print ("Line 3: $value")
_EOF_`

echo "$script" | python

Another variant of this construction:

python << END
... CODE ...
END

And another option, in which the output is assigned as the value of the ABC variable:

ABC=$(python << END ... END)

Leave Your Observation

Your email address will not be published. Required fields are marked *