简体   繁体   中英

Python: Variable not set when process sets it

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?

hasattr(state, 'websocketPort')为true时, state.websocketServer仅在initWebsocketServer定义为局部变量,而在主进程中则不会。

Well, it turned out that my edited part also didn't work, it just didn't throw an error and reached the end of the script. That's not all I wanted it to do... :)

I guess I tried to do something that is inconveniently hard to do . I switched to regular threading and hope that I don't run into those situations that processes can handle better than threads...

if hasattr(state, "websocketPort"):
  state.websocketServer = WebsocketServer(state.websocketPort)
  wst = threading.Thread(target = state.websocketServer.run_forever, daemon = True)
  wst.start()
else:
  print("dummy")
  def dummy(msg):
    pass
  state.websocketServer = type('', (), {})()
  state.websocketServer.send_message_to_all = dummy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM