<p>正如您在<a href="http://docs.python.org/2/reference/compound_stmts.html#the-with-statement" rel="nofollow">'with' statement documentation</a>中所看到的,it语句确实执行了一些与我们的目的相关的“魔术”。具体来说:</p>
<blockquote>
<p>The execution of the with statement with one “item” proceeds as
follows:</p>
<ol>
<li><p>The context expression (the expression given in the with_item) is evaluated to obtain a context manager.</p></li>
<li><p>The context manager’s <code>__exit__()</code> is loaded for later use.</p></li>
<li><p>he context manager’s <code>__enter__()</code> method is invoked.</p></li>
<li><p>If a target was included in the with statement, the return value from <code>__enter__()</code> is assigned to it.</p></li>
<li><p>The suite is executed.</p></li>
<li><p>The context manager’s <code>__exit__()</code> method is invoked. If an exception caused the suite to be exited, its type, value, and
traceback are passed as arguments to <code>__exit__()</code>. Otherwise, three None
arguments are supplied.</p></li>
</ol>
</blockquote>
<p>这是什么意思?如果仔细查看<a href="http://www.python.org/dev/peps/pep-3143/" rel="nofollow">the PEP in question</a>,它也可以作为python守护进程文档(而且确实可以得到很大改进),您将看到它实现了<code>__enter__()</code>和<code>__exit__()</code>:</p>
<blockquote>
<p>The class also implements the context manager protocol via <code>__enter__</code>
and <code>__exit__</code> methods.</p>
<p><strong><code>__enter__()</code></strong></p>
<p>Call the instance's open() method, then return the instance.</p>
<p><strong><code>__exit__(exc_type, exc_value, exc_traceback)</code></strong></p>
<p>Call the instance's close() method, then return True if the exception was handled or False if it was not.</p>
</blockquote>
<p>换句话说,不需要open(),PEP中给出的示例(尽管解释不正确)可以正常工作。虽然with语句确实有意义,但它不保留任何循环,一旦到达其作用域的末尾,它将调用<strong>exit</strong>(),这在python守护进程中是close()的意思。因此,你需要放置一段时间的真实或你认为无限循环。</p>
<p>关于你的第二个剧本不起作用的表现,我真的不能告诉你,我很惊讶第一个已经起作用了。如果守护进程正在停止,脚本肯定有问题,可以检查consumerDaemonLogFile。(另请注意,您键入了'sderr'-->;'stderr')</p>
<p>此外,您可以在PEP中看到,如果未指定,工作目录属性默认为“/”。如果在脚本中使用相对路径,这可能是问题的根源。</p>
<p>最后,关于最后一个问题,您可以很容易地杀死正在查找其PID的守护进程:</p>
<pre><code>ps ax | grep startConsumerDaemons.py
</code></pre>
<p>并发送一个SIGTERM:</p>
<pre><code>kill <pid>
</code></pre>
<p>gromain提供的答案确实提供了一种更方便的方法来启动和停止它,使用“daemon.runner()”,但是设置起来要复杂得多。</p>