D
D
dr sbtn2017-05-15 23:35:15
Python
dr sbtn, 2017-05-15 23:35:15

How to catch the execution code of a command sent in a python script to sh via subprocess?

having code on bash:

TIME=0
  sh -c "${команда, которую я выполняю}" > /dev/null 2>&1
  while test $? -ne 0 -a ${TIME} -lt ${TIMEOUT}
  do
    sleep 1
    TIME=`expr ${TIME} + 1`
    sh -c "${команда, которую я выполняю}" > /dev/null 2>&1
  done
  return $?

I'm trying to figure out how to implement this piece in python.
ok, I'm writing
T=0
subprocess.run(['sh',  'команда, которую я выполняю'], stdout=subprocess.PIPE)

and something I have further stupor completely. I was thinking of somehow catching the result of executing the command that I send to sh as a variable. (0 or 1, like a $? variable that I can use in the shell), but I have no idea if it can be done and how, if so.
where to look?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
javedimka, 2017-05-16
@dawasaturday

returncode = subprocess.run(['sh',  'команда, которую я выполняю'], stdout=subprocess.PIPE).returncode
print(returncode)

https://docs.python.org/3/library/subprocess.html
class subprocess.CompletedProcess
And maybe you should run subprocess.run() with shell=True argument

A
Alexander, 2017-05-16
@sanya84

Here is what you need

import subprocess

p = subprocess.Popen('sh ',  shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate('echo "Hello!"'.encode())
print(out.decode('cp866'),err.decode('cp866'))


p.wait()
input()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question