Enter to raw_input automatically

前端 未结 4 1802
傲寒
傲寒 2020-12-17 23:42

Just as an example, it might seem illogical. I have a get_name function as below, and wanted to write a automated script to call this function and enter to the raw_inp

4条回答
  •  一个人的身影
    2020-12-18 00:18

    You can redirect your stdin to a file , and then raw_input() would read from that file.

    Example -

    def run():
        import sys
        f1 = sys.stdin
        f = open('input.txt','r')
        sys.stdin = f
        get_name()
        f.close()
        sys.stdin = f1
    

    Please note, after you do - f = open('input.txt','r') and sys.stdin = f , raw_input() would read from the file.

    Once you are done with the get_name() call, close the file and restore the stdin using sys.stdin = sys.__stdin__ , if you want to restore it back to console input, otherise you can restore it to f1 , which would restore it to the state it was before test started.

    Please note, you should be careful when redirecting inputs like this.

提交回复
热议问题