Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python from shell and capture output

I have written a program in shell. And inside this shell script, I am calling a python script. That is working fine. I want my python script to return the output to the shell script. Is it possible? (I didnt get any such way on google). Can you please tell how to do that in case it is possible?

test.sh

#!/bin/bash
python call_py.py

and python script (call_py.py)

#!/usr/bin/python
if some_check:
    "return working"
else:
    "return not working"

How do I return from python and catch in shell?

like image 311
Aakash Goyal Avatar asked Jan 22 '16 06:01

Aakash Goyal


People also ask

How do I run a Python script from the shell?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do you execute a Python command in Linux and output?

A better way to get the output from executing a linux command in Python is to use Python module “subprocess”. Here is an example of using “subprocess” to count the number of lines in a file using “wc -l” linux command. Launch the shell command that we want to execute using subprocess. Popen function.


1 Answers

To get the output of a command in a variable, use process substitution:

var=$( cmd )

eg

var=$( ls $HOME )

or

var=$( python myscript.py)

The $() is (almost) exactly equivalent to using backticks, but the backticks syntax is deprecated and $() is preferred.

If your intent is to return a string 'working' or 'not working' and use that value in the shell script to determine whether or not the python script was successful, change your plan. It is much better to use a return value. eg, in python you 'return 0' or 'return 1' (zero for success, 1 for failure), and then the shell script is simply:

if python call_py.py; then
  echo success
else
  echo failure
fi
like image 53
William Pursell Avatar answered Oct 13 '22 12:10

William Pursell