Python – How do I import a python file in a bash script? (Using python values in my bash script)

How do I import a python file in a bash script? (Using python values in my bash script)… here is a solution to the problem.

How do I import a python file in a bash script? (Using python values in my bash script)

I

was wondering if it was possible to include a python script in a bash script to write (in a bash script) the return value of a function I wrote in a python program?

For example:
My file “file.py” has a function that returns the variable value “my_value” (representing the filename, but anyway)
I want to create a bash script that must be able to execute a command line like “ingest my_value”

So how do you know how to include a python file in a bash script (import …?) And how to call the values in the python file in a bash script?

Thank you in advance.

Update

Actually, my python file looks like this:

class formEvents():
    def __init__(self):
        ...
    def myFunc1(self): # function which returns the name of a file that the user choose in his computeur
    ...
    return name_file        

def myFunc2(self): # function which calls an existing bash script (bash_file.sh) in writing the name_file inside it (in the middle of a line)
        subprocess.call(['./bash_file.sh'])

if__name__="__main__":
    FE=formEvents()

I don’t know if it’s clear enough, but here’s my problem: it’s able to write name_file in bash_file.sh

Jordan

Solution

The easiest way to do this is through the standard the UNIX pipeline and your shell.

Here is an example:

foo.sh:

#!/bin/bash

my_value=$(python file.py)
echo $my_value

File .py:

#!/usr/bin/env python

def my_function():
    return "my_value"

if __name__ == "__main__":
    print(my_function())

The way it works is simple:

  1. You start the foo.sh
  2. Bash spawns a child process and runs the python file.py
  3. Python (and the interpretation of file.py) runs the function my_function and prints its return value to the Standard Output <
  4. Bash captures the “standard output” of Python processes in my_value
  5. Bash then simply echoes the value stored in the my_value to “standard output” as well, and you should see “my_value” printed to the shell/terminal.

Related Problems and Solutions