Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return string from Python to Shell script

I have Python code like:

x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)

if i == 0:
    print "ERROR"
elif i == 1:
    return str(some_var1)
else:
    print "OOOps"
    num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
    return str(num)

After I must execute this script in shell script and return string in shell variable, like:

VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)

Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer

like image 568
Андрей Далевский Avatar asked Jan 31 '26 10:01

Андрей Далевский


1 Answers

That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.

x, y = sys.argv[1:3]
i = sofe_def(x,y)

if i == 0:
    print >>sys.stderr, "ERROR"
elif i == 1:
    print str(some_var1)
else:
    print >>sys.stderr, "OOOps"
    print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
    num = raw_input()
    print num

(Note some other changes:

  1. Write your error messages to standard error, to avoid them being captured as well.
  2. Use raw_input, not input, in Python 2.

)

Then your shell

VAR1="foo"
VAR2="bar"

RES=$(python test.py "$VAR1" "$VAR2")

should work. Unless you have a good reason not to, always quote parameter expansions.

like image 93
chepner Avatar answered Feb 02 '26 22:02

chepner