Joe C
Joe C

Reputation: 2827

os.system does not allow a command with >

I can use the following command in linux.

ls > >(tee -a a)

But python os.system does not allow the syntax.

>>> import os
>>> os.system("ls > >(tee -a a)") sh: -c: line 0: syntax error near unexpected token `>' sh: -c: line 0: `ls > >(tee -a)' 256
>>>

Do we need any special ways to escape any chars?

Upvotes: 0

Views: 821

Answers (2)

aifos324
aifos324

Reputation: 98

os.system will be replaced by subprocess. Here is a solution with subprocess.Popen

import subprocess
process = subprocess.Popen("ls", stdout=subprocess.PIPE)
stdoutdata, _ = process.communicate()
print stdoutdata
with open ("a", "a") as fle:
    fle.write(stdoutdata)

Upvotes: 1

K. A. Buhr
K. A. Buhr

Reputation: 50829

As alluded to in a comment, os.system runs the command with /bin/sh. Even if this is a link to /bin/bash, when Bash is run as /bin/sh, it switches to a POSIX-conforming mode where Bash-specific syntax (like the command you're running) doesn't work.

One solution is to use:

os.system("/bin/bash -c 'ls > >(tee -a a)'")

This is pretty gross -- it uses the shell /bin/sh to run a new shell /bin/bash to run the desired command. If you really wanted to do this, using the functions in package subprocess to run Bash directly would be cleaner.

In this case, though, I think there's a simpler solution. The "pipe" syntax:

os.system("ls | tee -a a")

is /bin/sh-compatible, and I think it achieves the same thing you are trying to do here.

As noted in another comment, it isn't that hard to do this in pure Python, either:

# Python 3
with open("a", "a") as o:
    for f in os.listdir("."):
        print(f)
        print(f, file=o)

# Python 2
with open("a", "a") as o:
    for f in os.listdir("."):
        print f
        print >>o, f

Upvotes: 2

Related Questions