Python version of freopen()

后端 未结 5 1530
借酒劲吻你
借酒劲吻你 2020-12-29 10:58

Is there anything in python that can replicate the functionality of freopen() in C or C++? To be precise, I want to replicate the functionality of:

freopen(\         


        
相关标签:
5条回答
  • 2020-12-29 11:27

    This should help:

    import sys
    
    def freopen(filename, mode):
        if mode == "r":
            sys.stdin = open(filename, mode)
    
        elif mode == "w":
            sys.stdout = open(filename, mode)
    
    # ---- MAIN ----
    
    freopen("input.txt", "r")
    freopen("output.txt", "w")
    
    0 讨论(0)
  • 2020-12-29 11:29

    You may also want to look at the contextmanager decorator in contextlib for temporary redirection:

    from contextlib import contextmanager 
    import sys 
    
    @contextmanager
    def stdout_redirected(new_stdout):
        save_stdout = sys.stdout
        sys.stdout  = new_stdout
        try:
            yield
        finally:
            sys.stdout = save_stdout
    

    Example:

     with open(filename, "w") as f:
         with stdout_redirected(f):
             print "Hello"
    
    0 讨论(0)
  • 2020-12-29 11:30

    If you're working on *nix platform, you can write your own freopen.

    def freopen(f,option,stream):
        import os
        oldf = open(f,option)
        oldfd = oldf.fileno()
        newfd = stream.fileno()
        os.close(newfd)
        os.dup2(oldfd, newfd)
    
    import sys
    freopen("hello","w",sys.stdout)
    
    print "world"
    
    0 讨论(0)
  • 2020-12-29 11:34

    Try this:

    import sys
    sys.stdin = open('input.txt', 'r') 
    sys.stdout = open('output.txt', 'w')
    

    Text files are self explanatory. You can now run this code on Sublime Text or any other text editor.

    0 讨论(0)
  • 2020-12-29 11:38

    sys.stdout is simply file object, so, you can reopen it to another destination

    out = sys.stdout
    sys.stdout = open('output.txt', 'w')
    // do some work
    sys.stdout = out
    

    out is only for recovering sys.stdout destination to default after work (as suggested Martijn Pieters - you can recover it by using sys.__stdout__, or not recover at all, if you don't need it).

    0 讨论(0)
提交回复
热议问题