Actually I don't know what title I should give this question, because I'm rather new to Python and a few different things could be wrong here.
The idea is to create a websocket server in case a port is given and otherwise to create a dummy implementation.
The state.py
-module is simple and short:
_dbg = ""
main.py:
import getopt
import multiprocessing
import sys
import time
import state
try:
(opts, args) = getopt.getopt(sys.argv[1:], "p:", [ "ws-port=" ])
except getopt.GetoptError:
sys.exit(2)
for (opt, arg) in opts:
if opt in ("-p", "--ws-port"):
state.websocketPort = int(arg)
#########
# and now the important part:
#########
if hasattr(state, "websocketPort"):
def initWebsocketServer():
print("iWS-1")
state.websocketServer = WebsocketServer(state.websocketPort)
print("iWS-2")
state.websocketServer.run_forever()
print("iWS-3")
wsThread = multiprocessing.Process(target = initWebsocketServer, daemon = True)
wsThread.start()
else:
print("dummy")
def dummy(msg):
pass
state.websocketServer = type('', (), {})()
state.websocketServer.send_message_to_all = dummy
time.sleep(10) # not even a sleep makes it work!
state.websocketServer.send_message_to_all("hello")
print("done")
Shell:
$ python main.py -p 1234
iWS-1
iWS-2
Traceback (most recent call last):
File "main.py", line 38, in <module>
state.websocketServer.send_message_to_all("hello")
AttributeError: module 'state' has no attribute 'websocketServer'
$ python main.py
dummy
done
$
So all if
s, checks and the dummy implementation seems to work fine, but assigning the actual instance to the module variable does not. What's wrong here?
If there is a totally different or better approach to this, please let me know.
EDIT:
While trying to understand the effect of the different entities I came up with this:
if hasattr(state, "websocketPort"):
def initWebsocketServer():
print("iWS-1")
print("iWS-2")
state.websocketServer.run_forever()
print("iWS-3")
# this assignment was between the first two print()s earlier:
state.websocketServer = WebsocketServer(state.websocketPort)
wsThread = multiprocessing.Process(target = initWebsocketServer, daemon = True)
wsThread.start()
And it works... As there won't be more interaction other than calling the dummified method I guess I can keep this as a solution.
Or would there be something else broken?