0

Why does this code run successfully in the terminal (Ubuntu 12.04):

python -c "print 123" > >(tee stdout.txt)

But this code in python (2.7.5):

import os
os.system('python -c "print 123" > >(tee stdout.txt)') # same command

generates this error?

sh: -c: line 0: syntax error near unexpected token `>'
sh: -c: line 0: `python -c "print 123" > >(tee stdout.txt)'
Matt
  • 724
  • 4
  • 11
axelbrz
  • 783
  • 1
  • 7
  • 16
  • 1
    You need to pass the parameter `shell=True`. Better yet, use native python. Out of interest, why are you using `> >(tee ...)` rather than just `| tee`? – Tom Fenech Mar 27 '15 at 15:55
  • Thanks for the native python suggestion. Anyway, I want to solve the issue with any command (`echo hello` instead for example). If I try to pass parameter `shell=True` I get `TypeError: system() takes no keyword arguments` – axelbrz Mar 27 '15 at 16:03
  • I'm trying to run a command using this: http://stackoverflow.com/a/692407/1112654 This question is a simplified enough version of the problem. – axelbrz Mar 27 '15 at 16:06
  • @axelbrz: With `subprocess.call`, you can receive the stdout and stderr (separately) from the executed command, and then do whatever you want with them in Python. That's probably going to work out better in the end. – rici Mar 27 '15 at 16:40

1 Answers1

3

os.system invokes sh, which does not support bash's >(process substitution).

For compatibility reasons, this is true even when sh is provided by bash.

Instead, run bash explicitly:

import subprocess
subprocess.call(["bash", "-c", 'python -c "print 123" > >(tee stdout.txt)'])
that other guy
  • 116,971
  • 11
  • 170
  • 194