0

I have a Python script that will do

p = subprocess.Popen(["powershell.exe", "DirectoryOfA.batFile], stdin = PIPE, stdout = PIPE)

I also have

while True:
    now = time.localtime()
    if now[4] == 0:
        p.communicate(input = b'something')[0]
    output = str(p.stdout.readline())
    print(output)

so I can see the outputs that come out of it. inside the while loop I have an if statement that if it's true, I want it to send an input to the powershell but it doesn't actually send the input until another output is sent and I'm not sure why.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • How do you know that it doesn't send the input? – mkrieger1 Jan 08 '21 at 23:31
  • What do you intend to achieve by `if now[4] == 0`? Have you checked whether this condition is true when you expect it to? – mkrieger1 Jan 08 '21 at 23:33
  • the condition is true its just an example condition i have set, and it doesnt send the input because i can physically see that it doesnt do it, until another output is recieved, then it will send the input – Daniel Egorov Jan 08 '21 at 23:37
  • Well `readline()` blocks while it waits for something to read, and only then does the code loop around to the next `communicate()`. – mkrieger1 Jan 08 '21 at 23:42
  • ok that makes sense, how would i go about making it not wait if thats possible – Daniel Egorov Jan 08 '21 at 23:55
  • Maybe implement with asyncio - [https://docs.python.org/3/library/asyncio-subprocess.html](https://docs.python.org/3/library/asyncio-subprocess.html) – wwii Jan 09 '21 at 00:14
  • Or concurrent.futures - https://docs.python.org/3/library/concurrent.futures.html – wwii Jan 09 '21 at 00:21
  • Does [Python: How to read stdout of subprocess in a nonblocking way](https://stackoverflow.com/questions/36476841/python-how-to-read-stdout-of-subprocess-in-a-nonblocking-way) answer your question? – wwii Jan 09 '21 at 00:26
  • i figured that part out with threading, now im having another issue with p.communicate closing stdout and i dont want that – Daniel Egorov Jan 09 '21 at 01:07
  • `communicate` waits for end of program which closes `stdout`. If you want to run process all time then you have to use `p.stdin` and `p.stdout` instead of `communicate` - ie. `p.stdin.write( b'something' + b'\n' )` - sometimes it may need also `p.stdin.flush()` – furas Jan 09 '21 at 03:09

0 Answers0