0

I have a related question to this one. The command that I'd like to execute is this one:

program test.in > test.out

where program takes as input test.in and outputs test.out. In python, I do

import subprocess


subprocess.Popen([program] + ['test.in > test.out'])

yet I get the error

Cannot open file 'test.in > test.out' for reading. 

I've also tried

subprocess.Popen([program] + 'test.in > test.out'.split())

yet this results in the error

Cannot open file `>` for reading.

How do I need to modify my script without using shell=True, which would pose a security threat? Thanks.

Hermi
  • 350
  • 2
  • 5
  • 16

2 Answers2

0

You can do it like this, without changing command:

import subprocess

cmd = "program test.in > test.out"
proc = subprocess.Popen(cmd, shell=True)

Edited: As answer to a comment:

with open('test.out', 'w') as outfile:
    proc = subprocess.Popen(['program', 'test.in'], stdout=outfile)

This code splits the command "program test.in > test.out" into the list ['program', 'test.in']. It also redirects the output to a file named test.out using the stdout parameter.

  • 1
    > How do I need to modify my script without using `shell=True`, which would pose a security threat? – Hermi Apr 05 '23 at 19:40
-1

If the program takes them in as arguments, then you should just follow the normal syntax for Popen like this:

subprocess.Popen(['program', 'test.in', '>', 'test.out'])

Is there a reason you're not following this syntax?

SimonUnderwood
  • 469
  • 3
  • 12
  • Yes, there's a reason why I'm not following your suggestion. When I do as you suggested, I get the error `Cannot open file '>' for reading.` This is a bit of a pity, since `program` seems to interpret `>` as a file instead of an assignment operator to a file... – Hermi Apr 05 '23 at 20:00