Aakanksha Choudhary
Aakanksha Choudhary

Reputation: 625

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?

Upvotes: 0

Views: 113

Answers (1)

martineau
martineau

Reputation: 123501

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())

Upvotes: 1

Related Questions