在python中使用os.system但在shell中不使用时出错

时间:2016-06-13 08:34:30

标签: python linux bash shell

我正在尝试重定向gnu make。 想要将ALL重定向到STDOUT和all.log,只将错误重定向到error.log。

以下是我的程序

true

当我执行它时

data

但是在linux bash shell上执行相同的命令会毫无错误地执行。

#!/usr/bin/env python
import optparse
import os
import sys
import commands

command = 'make all > >(tee -a  all.log ) 2>&1 2> >(tee -a  error.log )'
SysReturnVal=os.system(command)

print "system return value is ", SysReturnVal

为什么在使用os.system在python脚本中运行时失败,但在终端/ bash shell中没有?

2 个答案:

答案 0 :(得分:0)

os.system()调用* nix system()来电。

  

system()库函数使用fork(2)来创建子进程          使用execl(3)执行命令中指定的shell命令          如下:              execl(" / bin / sh"," sh"," -c",command,(char *)0);

更多信息:doc

您必须执行os.system("/bin/bash <command>")

之类的操作

答案 1 :(得分:0)

os.system启动/bin/sh并且您的命令中存在基础:

>(....)

您需要启动bash:

os.system("bash -c '{}'".format(command))

另请记住,如果您在命令中使用单引号,则需要将其转义为打印:'\'',例如:

command="ls '\\''.'\\''"
# And it's even worse in single quotes:
command='ls \'\\\'\'.\'\\\'\''
相关问题