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:
- You start
the foo.sh
- Bash spawns a child process and runs
the python file.py
- Python (and the
interpretation of file.py
) runs the functionmy_function
and prints its return value to the Standard Output < - Bash captures the “standard output” of Python processes in
my_value
- 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.