0

In python, when I execute the commands

cmd = ['head', '-7', 'rres17.txt', '>', 'x']
subprocess.run(cmd)

I get the error message

head: cannot open ‘>’ for reading: No such file or directory
head: cannot open ‘x’ for reading: No such file or directory

When I execute the command

cmd = "head -7 rres17.txt > x"
subprocess.run(cmd)

I get the error message

FileNotFoundError: [Errno 2] No such file or directory: 'head -7 rres17.txt > x'

I'm using python version 3.5.2. How do I get subprocess to correctly execute this command, the way the documentation seems to indicate that it should? Thanks.

EDIT:

The following commands worked:

cmd = ['head', '-7', 'rres17.txt']
with open("x", "wb") as out: subprocess.Popen(cmd, stdout=out)

Thanks everyone.

1 Answers1

3

You cannot redirect stdout to a file like this, you need to use subprocess.run and redirect to a pipe.

See piping output of subprocess.Popen to files

For instance:

import subprocess
import io

with io.open('x', mode='wb') as fd:
    subprocess.run(['head', '-7', 'rres17.txt'], stdout=fd)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • I still get the same kind of error . Using [code] with open("x", "wb") as out: subprocess.Popen(cmd, stdout=out) `code` and removing the shell redirection gives the same error. –  Oct 13 '17 at 22:30