Calling Python from bash

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

Inline Python Code

Use bash here-doc:

  python3 <<EOF
print('blah')
EOF

Also see:

Python Script

Code in External Script

External Script

External Module

Given an external module my_module.py with the following content:

def my_function(arg1, arg2, arg3):
    print('this is my_function(' + arg1 + ", " + arg2 + ", " + arg3 + ")")

the module can be called generically from a bash script as follows:

#!/usr/bin/env bash

function call-python() {
  local python_interpreter=$1
  local module_path=$2
  local function_name=$3
  [[ -z ${python_interpreter} ]] && fail "'python_interpreter' not provided"
  [[ -z ${module_path} ]] && fail "'module_path' not provided"
  [[ -z ${function_name} ]] && fail "'function_name' not provided"
  shift 3
  local args
  for i in "${@}"; do
    [[ -z ${args} ]] && args="'${i}'" || args="${args}, '${i}'"
  done
  local module_name
  module_name=$(basename "${module_path}" .py)
  # instead of PATH python3 you may want to use the interpreter from a specific virtual environment
  (PYTHONPATH="$(dirname ${module_path})"; export PYTHONPATH; ${python_interpreter} <<EOF
import ${module_name}

${module_name}.${function_name}(${args})
EOF
  )
}

call-python ./my_module.py my_function blue red green

The output will be:

this is my_function(blue, red, green)

⚠️ Numbers will be converted to strings before being passed to the function, the implementation is incomplete.

Using the Interpreter from the a Virtual Environment

If you want to use the interpreter from a specific virtual environment instead of the interpreter found in PATH, explicitly use the path to the binary from the virtual environment directory:

$(dirname $0)/venv/bin/python ...

Execute a Complex Python Program as a Command Line Command

Embed logic into a Python program and invoke the program as a regular command, from a pipeline for example:

<syntaxhighlight lang='bash'> ./cicd/build-and-publish </syntaxhighlight