繁体   English   中英

如何使特定python命令的所有输出静音?

[英]how can I silence all of the output from a particular python command?

Autodesk Maya 2012提供了“mayapy” - 一个python的修改版本,其中包含加载Maya文件所需的软件包,并作为批量工作的无头3D编辑器。 我是用bash脚本调用的。 如果该脚本使用cmds.file(filepath, open=True)打开其中的场景文件,它会发出警告,错误和其他我不想要的信息的页面。 我希望把所有这些关在cmds.file命令运行。

我已经尝试从我在shell脚本中发送到mayapy的Python命令内部重定向,但这不起作用。 可以通过在调用bash脚本时将stdout / err重定向到/ dev / null 使所有内容静音。 有没有办法在调用shell时使它静音,但是仍然允许我在脚本中传入的命令打印出信息?

test.sh:

#!/bin/bash

/usr/autodesk/maya/bin/mayapy -c "
cmds.file('filepath', open=True);
print 'hello'
"

叫它:

$ ./test.sh                  # spews info, then prints 'hello'
$ ./test.sh > /dev/null 2>&1 # completely silent

基本上,我认为解决此问题的最佳方法是实现一个包装器,它将执行test.sh并清理输出到shell。 为了清理输出,我只是在前面添加一些字符串来通知你的包装器这个文本适合输出。 我对包装文件的灵感来自于: https//stackoverflow.com/a/4760274/2030274

内容如下:

import subprocess

def runProcess(exe):
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
      retcode = p.poll() #returns None while subprocess is running
      line = p.stdout.readline()
      yield line
      if(retcode is not None):
        break

for line in runProcess(['./test.sh']):
  if line.startswith('GARYFIXLER:'):
      print line,

现在你可以想象test.sh就是这样的东西

#!/bin/bash

/usr/autodesk/maya/bin/mayapy -c "
cmds.file('filepath', open=True);
print 'GARYFIXLER:hello'
"

这只会打印你好的线。 因为我们在子进程中包装python调用,所以通常显示给shell的所有输出都应该被捕获,你应该拦截你不想要的行。

当然,要从python脚本调用test.sh,您需要确保拥有正确的权限。

我知道我刚刚用管子扭曲了。 Maya确实将所有批量输出发送到stderror。 一旦你正确地管道stderr,这将完全释放stdout。 这是一个全效的单行程。

# load file in batch; divert Maya's output to /dev/null
# then print listing of things in file with cmds.ls()
/usr/autodesk/maya/bin/mayapy -c "import maya.standalone;maya.standalone.initialize(name='python');cmds.file('mayafile.ma', open=True);print cmds.ls()" 2>/dev/null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM