3

I would like to know if it's possible in a bash script to include a python script in order to write (in the bash script) the return value of a funnction I wrote in my python program ?

For example: my file "file.py" has a function which returns a variable value "my_value" (which represents the name of a file but anyway) I want to create a bash script which has to be able to execute a commande line like "ingest my_value"

So do you know how to include a python file in a bash script (import ...?) and how is it possible to call a value from a python file inside a bash script ?

Thank you in advance.

Update

Actually, my python file looks like that:

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 is my problem: it's to be able to write name_file inside the bash_file.sh

Jordane

  • Possible duplicate: http://stackoverflow.com/questions/24553728/collecting-return-values-from-python-functions-in-bash – ρss Jul 16 '14 at 11:38

3 Answers3

4

The easiest way of doing this is via the standard UNIX Pipeline and your Shell.

Here's 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 this works is simple:

  1. You launch foo.sh
  2. Bash spawns a subprocess and runs python file.py
  3. Python (and the interpretation of file.py) run the function my_function and print it's return value to "Standard Output"
  4. Bash captures the "Standard Output" of the Python process in my_value
  5. Bash then simply echoes the value stored in my_value also to "Standard Output" and you should see "my_value" printed to the Shell/Terminal.
Community
  • 1
  • 1
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • 1
    Thank you very much for your reply. I'll try to do some tests and if never I meet other problems, I'll write another post! :) –  Jul 16 '14 at 13:17
0

If the python script outputs the return value to the console, you should be able to just do this

my_value=$(command)

Edit: Damn, beat me to it

Matt
  • 968
  • 2
  • 13
  • 22
0

Alternatively, you can make the bash script process arguments.

#!/usr/bin/bash

if [[ -n "$1" ]]; then
     name_file="$1"
else
    echo "No filename specified" >&2
    exit 1
fi
# And use $name_file in your script

In Python, your subprocess call should be changed accordingly:

subprocess.call(['./bash_file.sh', name_file])
joepd
  • 4,681
  • 2
  • 26
  • 27