守护进程时不执行Python子进程

时间:2012-10-24 21:13:34

标签: python shell subprocess daemon popen

我尝试在父类被守护的方法中执行脚本。

autogamma.sh是一个需要安装(并使用转换)ImageMagick的脚本,可在此处找到:http://www.fmwconcepts.com/imagemagick/autogamma/index.php

import os
import subprocess
import daemon

class MyClass():
    def __init__(self):
        self.myfunc()
    def myfunc(self):
        script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'autogamma.sh')
        cmd = ('/bin/sh %s -c average /tmp/c.jpg /tmp/d.jpg' % script).split(' ')
        ret = subprocess.Popen(cmd).communicate()

with daemon.DaemonContext():
    process = MyClass()
    process.run()

仅在启动MyClass类时正确执行脚本。我认为env或类似的东西存在问题,但无法得到它。

Rsync,mediainfo,ffprobe也出现了问题。 使用Python 2.7.3与python-daemon 1.6,在mac os,centos 5.5,ubuntu 12.04TLS上测试

3 个答案:

答案 0 :(得分:2)

脚本非常简短,如果排除用于读取命令行参数,注释和其他颜色模式的代码,则它小于75行。我只想把它转换成Python。

与评论建议一样,最好的方法是使用ImageMagick的一个python包装器。

你也可以直接打电话给convert,虽然这可能会很痛苦。这是一个小小的片段:

import subprocess

def image_magick_version():
    output = subprocess.check_output("/usr/local/bin/convert -list configure", shell=True)

    for line in output.split('\n'):
        if line.startswith('LIB_VERSION_NUMBER'):           
            _, version = line.split(' ', 1)
            return tuple(int(i) for i in version.split(','))

im_version = image_magick_version()    
if im_version < (6,7,6,6) or im_version > (6,7,7,7) :
    cspace = "RGB"
else:
    cspace = "sRGB"

if im_version < (6,7,6,7) or im_version > (6,7,7,7):
    setcspace = "-set colorspace RGB"
else:
    setcspace = ""

答案 1 :(得分:0)

当我怀疑环境问题时,我会做以下两件事之一:

  1. 使用“env - whatever-script”在前台运行脚本。这个 应清除环境,并将错误发送到您的终端 标准错误,
  2. 正常运行脚本,但是将stdout和stderr重定向到a 文件在/ tmp:whatever-script&gt; / tmp / output 2&gt;&amp; 1
  3. 这使得无tty的脚本不那么不透明。

答案 2 :(得分:0)

我终于找到了问题。这是一个有效的道路问题。在查看了lib后,我找到了这个有用的参数:

    `working_directory`
        :Default: ``'/'``

        Full path of the working directory to which the process should
        change on daemon start.

        Since a filesystem cannot be unmounted if a process has its
        current working directory on that filesystem, this should either
        be left at default or set to a directory that is a sensible “home
        directory” for the daemon while it is running.

所以我设置了这样的守护进程:

with daemon.DaemonContext(working_directory='.'):
    process = MyClass()
    process.run()

现在我有正确的路径,我的脚本正确执行。