-1

Dollar question mark ($?) is used to find the return value of the last executed command and I want to use it in my script but it does not work.

python version : 3.7 Library : subprocess

I searched the answer but I can't find the suit answer in python.

I tried the following code, but it doesn't work :

#!/usr/bin/python
import subprocess
subprocess.call(["ls","-l"])
if $? == 0 :
    print("is ok\n")       
realr
  • 3,652
  • 6
  • 23
  • 34
Parsa
  • 3
  • 2
  • Does this answer your question? [Get a return value using subprocess](https://stackoverflow.com/questions/9041141/get-a-return-value-using-subprocess) – Simon Crane Jan 17 '20 at 15:48

2 Answers2

1

subprocess.call will return the code and you can store it inside variable:

import subprocess
rv = subprocess.call(["ls","-l"])  # <-- result of the call is stored inside `rv` variable
if rv == 0 :                       # <-- check the variable
  print("is ok")                   # <-- no need to put additional '\n' to print statement

Prints:

... the result of `ls -l`
is ok
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

call returns an object with a returncode attribute you can check.

result = subprocess.call(["ls", "-l"])
if result.returncode == 0:
    print("is ok")
chepner
  • 497,756
  • 71
  • 530
  • 681