如何在twisted tac文件中避免ImportError?

时间:2017-10-17 07:19:44

标签: python twisted

我有一个带有代码的扭曲的tac文件(twisted_service.py):

from twisted.application import service
# application.py file in the same dir
from .application import setup_reactor


class WebsocketService(service.Service):

    def startService(self):
        service.Service.startService(self)
        setup_reactor()

application = service.Application("ws")

ws_service = WebsocketService()
ws_service.setServiceParent(application)

这是application.py文件,它设置了reactor:

# -*- coding: utf-8 -*-
from twisted.web.server import Site
from twisted.web.static import Data
from twisted.internet import reactor, defer
from autobahn.twisted.resource import WebSocketResource
from autobahn.twisted.websocket import WebSocketServerFactory
from txsni.snimap import SNIMap
from txsni.maputils import Cache
from txsni.snimap import HostDirectoryMap
from twisted.python.filepath import FilePath
from tools.database.async import pg_conn
from tools.database import makedsn
from tools.config import main_db
from tools.modules.external import flask_setup


import tools.config as config
import websockethandlers as wsh
from pytrapd import TrapsListener


PROTOCOLMAP = {
    'portcounters': wsh.PortCounters,
    'eqcounters': wsh.EquipmentCounters,
    'settings': wsh.Settings,
    'refresh': wsh.Refresher,
    'montraps': wsh.TrapsMonitoring,
    'fdbs': wsh.FdbParser,
    'portstate': wsh.PortState,
    'cable': wsh.CableDiagnostic,
    'eqcable': wsh.EquipmentCableDiagnostic,
    'igmp': wsh.Igmp,
    'ipmac': wsh.IpMac,
    'lldp': wsh.LLDPParser,
    'alias': wsh.AliasSetup,
    'ping': wsh.Ping
}


@defer.inlineCallbacks
def setup_reactor():
    flask_setup()
    yield pg_conn.connect(makedsn(main_db))
    root = Data("", "text/plain")
    for key in PROTOCOLMAP:
        factory = WebSocketServerFactory("wss://localhost:%s" % config.ws_port)
        factory.protocol = PROTOCOLMAP[key]
        resource = WebSocketResource(factory)
        root.putChild(key, resource)
    site = Site(root)
    context_factory = SNIMap(
        Cache(HostDirectoryMap(FilePath(config.certificates_directory)))
    )
    reactor.listenSSL(config.ws_port, site, context_factory)
    traps_listener = TrapsListener()
    traps_listener.listen_traps(config.trap_ip)
    traps_listener.listen_messages(config.fifo_file)

if __name__ == '__main__':
    setup_reactor()
    import sys

    from twisted.python import log
    log.startLogging(sys.stdout)
    reactor.run()

我使用twistd -noy twisted_service.py命令来运行扭曲的服务。它一直在扭曲16.3.2版本。升级到任何下一个版本后,我收到错误:

Unhandled Error
Traceback (most recent call last):
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 662, in run
    runApp(config)
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/scripts/twistd.py", line 25, in runApp
    _SomeApplicationRunner(config).run()
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 380, in run
    self.application = self.createOrGetApplication()
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 445, in createOrGetApplication
    application = getApplication(self.config, passphrase)
--- <exception caught here> ---
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/app.py", line 456, in getApplication
    application = service.loadApplication(filename, style, passphrase)
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/application/service.py", line 412, in loadApplication
    application = sob.loadValueFromFile(filename, 'application')
  File "/home/kalombo/.virtualenvs/dev/local/lib/python2.7/site-packages/twisted/persisted/sob.py", line 177, in loadValueFromFile
    eval(codeObj, d, d)
  File "twisted_service.py", line 3, in <module>
    from .application import setup_reactor
exceptions.ImportError: No module named application

我应该如何正确运行扭曲或导入模块?

2 个答案:

答案 0 :(得分:1)

我几乎找到了你的答案。如下:

import os
import sys

sys.path = [os.path.join(os.getcwd(), '.'), ] + sys.path

只需将当前工作目录添加到sys.path。

但我没有找到更好的方法....我认为这不是很好。

答案 1 :(得分:0)

我在这里找到了答案TimeOfDay

这是Twisted 16.4.0中的新功能。在以前的版本中,twistd脚本自动将工作目录添加到系统路径,从16.4.0版本我必须手动添加它。可以在twisted_service.py文件中添加类似的内容:

import os
import sys
TWISTED_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(TWISTED_DIR)