Python: equivalent of input using sys.stdin

余生颓废 提交于 2019-12-06 09:24:06

input() only does the magic you mentioned when stdin and stdout are not altered, because only then it can use things like the readline library. If you replace them with something else (real-files or not) it comes down to this code:

/* Fallback if we're not interactive */
if (promptarg != NULL) {
    if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
         return NULL;
}
tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
if (tmp == NULL)
    PyErr_Clear();
else
    Py_DECREF(tmp);
return PyFile_GetLine(fin, -1);

Where PyFile_GetLine calls the readline method. Thus mocking sys.std* will work.

It's recomended you do this with try: finally:, a context processor or the mock module, so that the outputs are restored even if the code you are testing fails with exceptions:

from unittest.mock import patch
from io import StringIO

with patch("sys.stdin", StringIO("FOO")), patch("sys.stdout", new_callable=StringIO) as mocked_out:
    x = input()
    print("Read:", x)

assert mocked_out.getvalue() == "Read: FOO\n"

If you assign a file-like object to sys.stdin Python's input function will use it instead of the standard input. But remember to reassign sys.stdin back to the standard input after you're done with it. The same trick applies to sys.stdout. You can do something like this:

original_stdin = sys.stdin
sys.stdin = open('inputfile.txt', 'r')

original_stdout = sys.stdout
sys.stdout = open('outputfile.txt', 'w')

response = input('say hi: ')
print(response)

sys.stdin = original_stdin
sys.stdout = original_stdout

These two lines

response = input('say hi: ')
print(response)

will use specified files (inputfile.txt and outputfile.txt) instead of the standard input and standard output.

UPDATE: If you don't want to deal with physical files take a look at io module. It provides io.StringIO class which allows you to perform in-memory text stream operations.

original_stdin = sys.stdin
sys.stdin = io.StringIO('input string')

original_stdout = sys.stdout
sys.stdout = io.StringIO()

response = input('say hi: ')
print(response)

output = sys.stdout.getvalue()

sys.stdin = original_stdin
sys.stdout = original_stdout

print(output)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!