Cameron Thompson
Cameron Thompson

Reputation: 9

subprocess.call() problems using the '>'

I'm having trouble with the call function

I'm trying to redirect the output of a program to a text file by using the '>'

This is what I've tried:

import subprocess

subprocess.call(["python3", "test.py", ">", "file.txt"])

but it still displaying the output on the command prompt and not in the txt file

Upvotes: 0

Views: 55

Answers (1)

John1024
John1024

Reputation: 113934

There are two approaches to solving this.

  1. Have python handle the redirection:

    with open('file.txt', 'w') as f:
        subprocess.call(["python3", "test.py"], stdout=f)
    
  2. Have the shell handle redirection:

    subprocess.call(["python3 test.py >file.txt"], shell=True)
    

Generally, the first is to be preferred because it avoids the vagaries of the shell.

Lastly, you should look into the possibility that test.py can be run as an imported module rather than calling it via subprocess. Python is designed so that it is easy to write scripts so that the same functionality is available either at the command line (python3 test.py) or as a module (import test).

Upvotes: 3

Related Questions