【问题标题】:How do I import modules when using Twisted subprocesses and virtualenvwrapper?使用 Twisted 子进程和 virtualenvwrapper 时如何导入模块?
【发布时间】:2015-02-14 18:43:09
【问题描述】:

我正在尝试在 Twisted 中编写一个 Web 服务器,它接受用户输入并根据输入绘制图像。

对于服务器,我有一个简单的 Twisted Web 服务器。 为了处理图像绘制,我使用 python wand。 我正在一个安装了 Twisted 和 Wand 的 virtualenvwrapper 中工作。但是,当我运行服务器时,出现导入错误:

Traceback (most recent call last):
  File "insert_bubble.py", line 1, in <module>
    from wand.image import Image
ImportError: No module named wand.image

如果我使用 python 解释器,我可以 import twistedimport wand.image 很好。我怀疑子进程没有使用正确的环境。一种解决方法是将子进程使用的所有模块安装到我的用户帐户中,但我想避免这种情况。

服务器代码大部分取自Twisted tutorial页面。

import sys
from twisted.internet import protocol
from twisted.internet import reactor
import re

class MyPP(protocol.ProcessProtocol):
    def __init__(self, verses):
        self.verses = verses
        self.data = ""
    def connectionMade(self):
        print "connectionMade!"
        self.transport.closeStdin() # tell them we're done
    def outReceived(self, data):
        print "outReceived! with %d bytes!" % len(data)
        self.data = self.data + data
    def errReceived(self, data):
        print "errReceived! with %d bytes!" % len(data)
        self.data= self.data+data
    def inConnectionLost(self):
        print "inConnectionLost! stdin is closed! (we probably did it)"
    def outConnectionLost(self):
        print "outConnectionLost! The child closed their stdout!"
        # now is the time to examine what they wrote
        print "I saw them write:", self.data
        #(dummy, lines, words, chars, file) = re.split(r'\s+', self.data)
        #print "I saw %s lines" % lines
    def errConnectionLost(self):
        print "errConnectionLost! The child closed their stderr."
    def processExited(self, reason):
        print "processExited, status %d" % (reason.value.exitCode,)
    def processEnded(self, reason):
        print "processEnded, status %d" % (reason.value.exitCode,)
        print "quitting"
        reactor.stop()

pp = MyPP(10)
reactor.spawnProcess(pp, sys.executable, ['python', 'insert_bubble.py'], {})
reactor.run()

如何让子进程使用正确的 virtualenv Python 安装,而不是我的家庭环境?

【问题讨论】:

    标签: python twisted virtualenv virtualenvwrapper


    【解决方案1】:

    而不是像这样运行子进程:

    reactor.spawnProcess(
        pp, sys.executable, ['python', 'insert_bubble.py'], {}
    )
    

    像这样运行它:

    reactor.spawnProcess(
        pp, sys.executable, ['python', 'insert_bubble.py'], os.environ
    )
    

    这会将父进程环境复制到子进程中,而不是使用空环境启动子进程。

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 2012-02-06
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      相关资源
      最近更新 更多