You can patch the module's function e.g. mymodule.input = myfunc
, then your function will be called and afterwards just return a string from your function.
# mymodule
def func():
print(input())
# main
import mymodule
def custom():
return "my custom input"
mymodule.input = custom
mymodule.func()
however this might need to happen before mymodule
is imported anywhere else. Depending on how the input()
is called (e.g. as a global call in a module thus (import module
already calling it indirectly) vs in a function, when it'd look into the globals()
which would be patched)
Now, there's an alternative with deeper patching, but we can't do much as input()
is a built-in and implemented in C (so not much of a patching available :( ). We can, however, utilize a custom sys.stdin
such as io.StringIO()
by which you can write to own "stdin" (it's not the real process' STDIN, just a buffer replacement, but that doesn't matter for this use-case).
Then a simple sys.stdin.write()
with rewinding will do (again, has to happen before input()
is called:
import sys
from io import StringIO
sys.stdin = StringIO()
sys.stdin.write("myinput")
sys.stdin.seek(0) # rewind, so input() can read
text = input()
print(f"{text=}")
Between processes, as you've mentioned, use PIPE
from subprocess
or similar module.