Search code examples
pythonsystem

How to save cmd output to text file through another script python


I am able to save the cmd data onto a text file using the following command:

python code_3.py > output.txt

However I am calling code_3.py from primary_script.py by writing:

import code_3
os.system('loop3.py')

But I want it to perform the functionality of the what the previous line does. This doesn't work:

os.system('loop3.py > opt.txt ')

Can someone please tell me what to do?


Solution

  • Here's how to do it with the subprocess module:

    import subprocess
    import sys
    
    p1 = subprocess.Popen([sys.executable, "loop3.py"], stdout=subprocess.PIPE)
    output, err = p1.communicate()
    
    with open('opt.txt', 'w') as file:
        file.write(output.decode())