Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables from python script to bash script

I have a bash script, a.sh , and in it I have call a python script b.py . The python script calculates something, and I want it to return a value that will be used later in a.sh . I know I can do

In a.sh:

var=`python b.py`

In b.py:

print x # when x is the value I want to pass

But this is not so convenient, because I also print other messages in b.py

Is there any better way to do it?

Edit:

What I'm doing now is just

var=`python b.py | tail -n 1`

It means I can print many things inside b.py, but only the last line (the last print command, assuming it doesn't contain "\n" in it) will be stored in var.

Thanks for all the answers!

like image 679
Rivka Avatar asked Nov 23 '10 14:11

Rivka


People also ask

How do you pass a variable to a shell script in Python?

You'll need to share what you've tried so far, or what the current code you have is. Try to keep it to the relevant portions, and not the entire script. Pass the variables into python as command line arguments then use something like getopt to parse the command line arguments within your python script.

Can you run a Python script in a bash script?

We can make use of the bash script to run the Python script in macOS/Ubuntu. Both these operating systems support bash scripts.

How do you pass arguments to function while executing a Python script from terminal?

The best choice is using the argparse module, which has many features you can use. So you have to parse arguments in your code and try to catch and fetch the arguments inside your code. You can't just pass arguments through terminal without parsing them from your code.

How do you store output of a Python script in a variable?

How to store a python script output to a variable using publish in workflow scripts. When you use Python script as action, you must implement run() method from BaseAction class. This method's return value can be assigned to the variable in the workflow. where msg being a variable declared in the orchesta workflow.


1 Answers

I would print it to a file chosen on the command line then I'd get that value in bash with something like cat.

So you'd go:

python b.py tempfile.txt
var=`cat tempfile.txt`
rm tempfile.txt

[EDIT, another idea based on other answers]

Your other option is to format your output carefully so you can use bash functions like head/tail to pipe only the first/last lines into your next program.

like image 141
Chris Pfohl Avatar answered Sep 18 '22 04:09

Chris Pfohl