How to execute a python script and write output to txt file?

后端 未结 8 601
离开以前
离开以前 2020-12-10 14:31

I\'m executing a .py file, which spits out a give string. This command works fine

execfile (\'file.py\')

But I want the output (in addition to it being shown

8条回答
  •  借酒劲吻你
    2020-12-10 15:06

    This'll also work, due to directing standard out to the file output.txt before executing "file.py":

    import sys
    
    orig = sys.stdout
    with open("output.txt", "wb") as f:
        sys.stdout = f
        try:
            execfile("file.py", {})
        finally:
            sys.stdout = orig
    

    Alternatively, execute the script in a subprocess:

    import subprocess
    
    with open("output.txt", "wb") as f:
        subprocess.check_call(["python", "file.py"], stdout=f)
    

    If you want to write to a directory, assuming you wish to hardcode the directory path:

    import sys
    import os.path
    
    orig = sys.stdout
    with open(os.path.join("dir", "output.txt"), "wb") as f:
        sys.stdout = f
        try:
            execfile("file.py", {})
        finally:
            sys.stdout = orig
    

提交回复
热议问题