Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a shell script function/variable from python?

Tags:

python

bash

Is there any way to call a shell script and use the functions/variable defined in the script from python?

The script is unix_shell.sh

#!/bin/bash
function foo
{
...
}

Is it possible to call this function foo from python?

Solution:

  1. For functions: Convert Shell functions to python functions
  2. For shell local variables(non-exported), run this command in shell, just before calling python script:
    export $(set | tr '\n' ' ')

  3. For shell global variables(exported from shell), in python, you can: import os print os.environ["VAR1"]

like image 640
Neerav Avatar asked Apr 16 '13 20:04

Neerav


4 Answers

Yes, in a similar way to how you would call it from another bash script:

import subprocess
subprocess.check_output(['bash', '-c', 'source unix_shell.sh && foo'])
like image 160
Eric Avatar answered Sep 28 '22 09:09

Eric


This can be done with subprocess. (At least this was what I was trying to do when I searched for this)

Like so:

output = subprocess.check_output(['bash', '-c', 'source utility_functions.sh; get_new_value 5'])

where utility_functions.sh looks like this:

#!/bin/bash
function get_new_value
{
    let "new_value=$1 * $1"
    echo $new_value
}

Here's how it looks in action...

>>> import subprocess
>>> output = subprocess.check_output(['bash', '-c', 'source utility_functions.sh; get_new_value 5'])
>>> print(output)
b'25\n'
like image 38
ChicagoCyclist Avatar answered Sep 28 '22 07:09

ChicagoCyclist


No, that's not possible. You can execute a shell script, pass parameters on the command line, and it could print data out, which you could parse from Python.

But that's not really calling the function. That's still executing bash with options and getting a string back on stdio.

That might do what you want. But it's probably not the right way to do it. Bash can not do that many things that Python can not. Implement the function in Python instead.

like image 34
Lennart Regebro Avatar answered Sep 28 '22 08:09

Lennart Regebro


With the help of above answer and this answer, I come up with this:

import subprocess
command = 'bash -c "source ~/.fileContainingTheFunction && theFunction"'
stdout = subprocess.getoutput(command)
print(stdout)

I'm using Python 3.6.5 in Ubuntu 18.04 LTS.

like image 42
M Imam Pratama Avatar answered Sep 28 '22 07:09

M Imam Pratama