2

I want to run a script using a subprocess inside a main script which would give a few lines of text as a result and then copy the results to a text file. I am using Python 2.7.

The folder where I want to run the secondary script is a different one from the folder where the main script is located, so I am following this answer where it is explained how to do this.

My code looks like the following:

import subprocess

if __name__=="__main__":
    subprocess.check_call(['top > test.txt'], cwd=newdirectory)

In this case I am just using top as an example of what I want to do. If I write top > test.txtin my terminal I get a text file called test.txt with the output of top at the moment of execution of the command.

But if I run the code that I posted above I get an error. I have also tried to use something like:

import subprocess

if __name__=="__main__":
    subprocess.check_call(['top', '> test.txt'], cwd=newdirectory)

But this doesn't give anything either (which makes sense as >test.txt is not an argument for the top command.

How can I write the output of the script (or in this case top) to the file test.txt in the new directory?

Community
  • 1
  • 1
S -
  • 349
  • 3
  • 19

0 Answers0