Oct-01-2020, 11:35 AM
I was trying to accept timed input when I noticed that Windows did not behave as I expected. A simplified version of the code to demonstrate this is below:
if __name__ == '__main__': statement.
While making sure that everything is indented under something will avoid the problem I was curious if this is actually the correct or even accepted behaviour. Note that the original program did not have the if __name__ == '__main__': and its behaviour was a lot stranger.
import multiprocessing, sys, os
def _input_with_timeout_process(stdin_file_descriptor, queue, prompt):
sys.stdin = os.fdopen(stdin_file_descriptor)
queue.put(input(prompt))
return
print("=== 1 ===", 'parent process:', os.getppid(), 'my pid:', os.getpid())
if __name__ == '__main__':
queue = multiprocessing.Queue()
process = multiprocessing.Process(target=_input_with_timeout_process,
args=(sys.stdin.fileno(), queue, "Say something: "))
process.start()
try:
process.join(10)
if process.is_alive():
raise ValueError("Timed out waiting for input.")
print("I saw:", queue.get())
except ValueError:
print("Sorry, too slow.")
finally:
process.terminate()Running this with Python 3.8.2 on Ubuntu 20.04 gives:Output:direl@MD-3670:~/Shared$ python min_mp_test.py
=== 1 === parent process: 30833 my pid: 32234
Say something: g
I saw: g
direl@MD-3670:~/Shared$However on Windows 10 with Python 3.8.6 I getOutput:PS C:\Users\mdavi\Documents> python z:min_mp_test.py
=== 1 === parent process: 4288 my pid: 5408
=== 1 === parent process: 5408 my pid: 5764
Say something: f
I saw: f
PS C:\Users\mdavi\Documents>It looks as though the second process is escaping from its function definition and executing any subsequent code that is not in either a function definition or anif __name__ == '__main__': statement.
While making sure that everything is indented under something will avoid the problem I was curious if this is actually the correct or even accepted behaviour. Note that the original program did not have the if __name__ == '__main__': and its behaviour was a lot stranger.
