Python Forum

Full Version: STDIN not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all.

Anyone would have an idea why the STDIN is not working here? I start a server application for a game as a subprocess, and the STDOUT part works and can read all the output, but the process.stdin.write doesn't do anything. (If I add process.communicate() after that line, it will work once and no more. I understand tho that 'communicate' shouldn't be used here since I want to keep sending commands, just mentioning it.)

def READ_CONSOL():
    while True:
        LINE = process.stdout.readline().rstrip()
        print((LINE.decode().strip()))

process = subprocess.Popen([r"C:\Games\Far Cry 2 Fortune's Edition\bin\FC2ServerLauncher.exe", "-noredirectstdin"], stdout = subprocess.PIPE, stdin = subprocess.PIPE)

start_new_thread(READ_CONSOL, ())

while True:
    COMMAND = input()
    process.stdin.write((COMMAND + '\n').encode())
(The "-noredirectstdin" part is a command line parameter the app needs to be launched with for STDIN to work, according to it's readme.)

Another question I would have is how I could make the subprocess close/terminate automatically when I close the main window.

Thanks in advance!
Try adding a flush after the write.

while True:
    COMMAND = input()
    process.stdin.write((COMMAND + '\n').encode())
    process.stdin.flush()
(Sep-04-2021, 01:22 PM)H84Gabor Wrote: [ -> ]Another question I would have is how I could make the subprocess close/terminate automatically when I close the main window.

Could try putting your code in a try/finally block and kill the subprocess in the finally block.


import time


def event_loop():
    count = 0
    while True:
        count += 1
        print(f"Counting: {count}")
        time.sleep(1)


try:
    event_loop()
finally:
    print("I'm done!")
    # kill the subprocess from here
Thank you!

The 'process.stdin.flush()' worked great! About the second thing I think I was a bit confused. What I wanted to do was to make that 'FC2ServerLauncher.exe' application terminate somehow when the consol the messages are printed to is closed. But I think to do that I would need to make that window also a subprocess so the pyhton script can detect it was closed and terminate the application and itself.