i'm try to run twistd web with Klein and got a lot of issues. Even if try run it from an example - got the same results. Source
from klein import Klein
app = Klein()
@app.route('/')
def hello(request):
return "Hello, world!"
resource = app.resource
Then run it (in this example, the file above is saved as twistdPlugin.py:
$ twistd -n web --class=twistdPlugin.resource
Errors:
sh-3.2# twistd -n web --class=twistdPlugin.resource
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/bin/twistd", line 11, in <module>
load_entry_point('Twisted==17.9.0', 'console_scripts', 'twistd')()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/scripts/twistd.py", line 29, in run
app.run(runApp, ServerOptions)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/application/app.py", line 657, in run
config.parseOptions()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/application/app.py", line 624, in parseOptions
usage.Options.parseOptions(self, options)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/python/usage.py", line 267, in parseOptions
self.subOptions.parseOptions(rest)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/python/usage.py", line 255, in parseOptions
self._dispatch[optMangled](optMangled, arg)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/python/usage.py", line 411, in <lambda>
fn = lambda name, value, m=method: m(value)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/web/tap.py", line 121, in opt_class
classObj = reflect.namedClass(className)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/python/reflect.py", line 173, in namedObject
module = namedModule('.'.join(classSplit[:-1]))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/twisted/python/reflect.py", line 159, in namedModule
topLevel = __import__(name)
ModuleNotFoundError: No module named 'twistdPlugin'
How to be with this?
You can solve this 1 of 2 ways. First way would be to add the directory with your source code to the PYTHONPATH
environment variable. This is the easiest method.
PYTHONPATH=$(pwd) twistd -n web --class twistdPlugin.resource
Or you could make a virtualenv and install your twistdPlugin
module there. This way you won't have to mess with environment variables yourself.
The tl;dr of the matter is that twistd used to source the current directory in Python 2 Twisted < 16.4 but it doesn't do that anymore with Python 3 the lastest Twisted. In other words, twistd expects all modules to be importable. Despite being a nuisance at times, this design makes twistd apps portable.