Calling Python from bash: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 30: Line 30:
   local module_path=$1
   local module_path=$1
   local function_name=$2
   local function_name=$2
   local arg1=$3
  shift 2
  local arg2=$4
   local args
   local arg3=$5
  for i in "${@}"; do
    [[ -z ${args} ]] && args="'${i}'" || args="${args}, '${i}'"
   done
   local module_name
   local module_name
   module_name=$(basename "${module_path}" .py)
   module_name=$(basename "${module_path}" .py)
Line 38: Line 40:
import ${module_name}
import ${module_name}


${module_name}.${function_name}('${arg1}', '${arg2}', '${arg3}')
${module_name}.${function_name}(${args})
EOF
EOF
   )
   )
Line 45: Line 47:
call-python ./my_module.py my_function blue red green
call-python ./my_module.py my_function blue red green
</syntaxhighlight>
</syntaxhighlight>
The output will be:  
The output will be:  
<syntaxhighlight lang='text'>
<syntaxhighlight lang='text'>
this is my_function(blue, red, green)
this is my_function(blue, red, green)
</syntaxhighlight>
</syntaxhighlight>
⚠️ <Font color=darkkhaki>Numbers will be converted to strings before being passed to the function, the implementation is incomplete.</font>


=Using the Interpreter from the a Virtual Environment=
=Using the Interpreter from the a Virtual Environment=

Revision as of 00:32, 16 February 2022

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 module_path=$1
  local function_name=$2
  shift 2
  local args
  for i in "${@}"; do
    [[ -z ${args} ]] && args="'${i}'" || args="${args}, '${i}'"
  done
  local module_name
  module_name=$(basename "${module_path}" .py)
  (PYTHONPATH="$(dirname ${module_path})"; export PYTHONPATH; python3 <<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 ...