-3

There are questions like this, that show how to interact with a shell in Python, sending stuff to its stdin and reading back stuff from its stdout.

I'd just like to do one more thing on top of that:

  • Start a process running a shell -- say: subprocess.Popen(["powershell --someArgs"])
  • interact with that shell/process by:
    • sending it the occasional command through stdin (commands that can take a while and spew a lot of output)
    • consume each command's output through stdout,
    • Identify when each command completes and and get the return code for each command, to know which ones succeed or fail.

I suspect there's no way to do the last part, other than to have the shell itself print its last return code, and have the parent parse that from stdout (also, scanning stdout for the prompt to know when the command finishes?). But I'm asking anyways...

Code samples are welcome but not necessary -- precise descriptions should be good enough :-)

(Ideally, using built-in modules like subprocess, without needing to install any new packages.)

SoreDakeNoKoto
  • 1,175
  • 1
  • 9
  • 16

1 Answers1

-1

That's on the contrary the easiest part.

When the subprocess terminates, it sends its exit code. It is the return value of wait method

import subprocess
p=subprocess.Popen(['sh', '-c', 'sleep 5 ; exit 12'])
x=p.wait()
print(f'exit code was {x}')

Note that you are not forced to literally wait the process for this to work. You can "wait" it after it is done, and do some other task in your python process in between (parallelism being one of the reasons why you may call subprocesses)

import subprocess
import time
p=subprocess.Popen(['sh', '-c', 'sleep 5 ; exit 12'])
time.sleep(10) # or anything else. The point is `.wait` is called after the process has returned
x=p.wait()
print(f'exit code was {x}')
chrslg
  • 9,023
  • 5
  • 17
  • 31
  • No, as mentioned, I need to send multiple commands into the *same* process/session and get their respective outputs/return codes -- that's what makes this tricky. – SoreDakeNoKoto Nov 19 '22 at 00:28
  • @SoreDakeNoKoto I read, and read angain your question after this comment of yours. And I still don't see where do you say that. You want multiple command in a single process? There is no such thing! If you run several command, then you run several processes. – chrslg Dec 02 '22 at 06:46
  • What is a terminal but a single process that runs multiple commands interactively? In any case, you're not obliged to answer -- It's perfectly fine to delete your answer and ignore this question. – SoreDakeNoKoto Dec 02 '22 at 23:20