Prev: [ANN] pyxser-1.3r-p1 --- Python XML Serialization/Deserialization Extension
Next: Float precision and float equality
From: candide on 4 Dec 2009 18:31 How do I redirect stdin to a text file ? In C, this can be done with the freopen() standard function, for instance FILE *foo = freopen("in.txt", "r", stdin); redirects stdin to the in.txt text file. Does anyone know a freopen() Python equivalent ? Notice that I'm not referring to shell redirection as the following command line shows : $ python myCode.py < in.txt I need to hardcode the redirection inside the python source file.
From: Lie Ryan on 4 Dec 2009 18:57 On 12/5/2009 10:31 AM, candide wrote: > How do I redirect stdin to a text file ? In C, this can be done with the > freopen() standard function, for instance > > FILE *foo = freopen("in.txt", "r", stdin); > > > redirects stdin to the in.txt text file. Does anyone know a freopen() > Python equivalent ? > > Notice that I'm not referring to shell redirection as the following > command line shows : > > $ python myCode.py< in.txt > > I need to hardcode the redirection inside the python source file. I'm not sure how freopen() works in C, but perhaps you're looking for redirecting sys.stdin: import sys old_stdin = sys.stdin # save it, in case we need to restore it sys.stdin = open('myfile') you can also restore stdin using sys.__stdin__ instead of saving the old one, but in the case you or someone else is redirecting the stdin twice...
From: MRAB on 4 Dec 2009 18:59 candide wrote: > How do I redirect stdin to a text file ? In C, this can be done with > the freopen() standard function, for instance > > FILE *foo = freopen("in.txt", "r", stdin); > > > redirects stdin to the in.txt text file. Does anyone know a freopen() > Python equivalent ? > > Notice that I'm not referring to shell redirection as the following > command line shows : > > $ python myCode.py < in.txt > > I need to hardcode the redirection inside the python source file. The standard input is sys.stdin and the standard output is sys.stdout. sys.stdin.close() sys.stdin = open("in.txt", "r")
From: candide on 4 Dec 2009 19:29
@MRAB @Lie Ryan Thanks, it works fine ! |