How to solve ValueError('Invalid async_mode specified') for flask-socketio? - socket.io

I'm testing a flask-socketio server in bitbucket pipeline. It failed with the following messages:
Traceback (most recent call last):
File "/root/.local/share/virtualenvs/build-3vGKWv3F/lib/python3.7/site-packages/flask_failsafe.py", line 29, in wrapper
return func(*args, **kwargs)
File "/opt/atlassian/pipelines/agent/build/main.py", line 89, in create_app
return cell_data_api.create_app()
File "/opt/atlassian/pipelines/agent/build/cell_data_api/__init__.py", line 30, in create_app
socketio.init_app(app)
File "/root/.local/share/virtualenvs/build-3vGKWv3F/lib/python3.7/site-packages/flask_socketio/__init__.py", line 243, in init_app
self.server = socketio.Server(**self.server_options)
File "/root/.local/share/virtualenvs/build-3vGKWv3F/lib/python3.7/site-packages/socketio/server.py", line 127, in __init__
self.eio = self._engineio_server_class()(**engineio_options)
File "/root/.local/share/virtualenvs/build-3vGKWv3F/lib/python3.7/site-packages/engineio/server.py", line 145, in __init__
raise ValueError('Invalid async_mode specified')
ValueError: Invalid async_mode specified
Traceback (most recent call last):
File "/.pyenv/versions/3.7.4/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/.pyenv/versions/3.7.4/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/opt/atlassian/pipelines/agent/build/main.py", line 117, in <module>
socketio.run(APP, host='0.0.0.0', port=8080, debug=True, use_reloader=True)
File "/root/.local/share/virtualenvs/build-3vGKWv3F/lib/python3.7/site-packages/flask_socketio/__init__.py", line 564, in run
if app.debug and self.server.eio.async_mode != 'threading':
AttributeError: 'NoneType' object has no attribute 'eio'
My main.py file looks like:
import os
from cell_data_api import socketio
# Detect if we are running in App Engine
# Make sure this does NOT start if we are running a Cloud Function
if os.getenv('APP_ENGINE', '') == 'TRUE':
import cell_data_api
APP = cell_data_api.create_app()
if __name__ == '__main__':
from flask_failsafe import failsafe
#failsafe
def create_app():
# note that the import is *inside* this function so that we can catch
# errors that happen at import time
import cell_data_api
# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
return cell_data_api.create_app()
APP = create_app()
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
socketio.run(APP, host='0.0.0.0', port=8080, debug=True, use_reloader=True)
Main.py imports from cell_data_api.py, which looks like:
import os
from flask import Flask
from flask_cors import CORS
# import eventlet
from engineio.async_drivers import eventlet
from flask_socketio import SocketIO
socketio = SocketIO(
always_connect=True,
logger=True,
async_mode=eventlet,
cookie=...,
ping_timeout=...
)
def create_app():
# create and configure the app
app = Flask(__name__)
CORS(app)
......
socketio.init_app(app)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
return app
My environment is Python 3.7 with installation packages:
[dev-packages]
alembic = "*"
flask_failsafe = "*"
wcwidth = "*"
[packages]
flask = "*"
absl-py = "*"
flask-cors = "*"
grpcio = "*"
transitions = "*"
sqlalchemy-json = "*"
sqlalchemy = "1.3.0"
flask_socketio='*'
eventlet='*'
Unlike the other two questions I found about the same error, I'm not using pyinstaller or cx_Freeze.

The async_mode parameter takes a string as an argument.
Instead of this:
async_mode=eventlet,
Do this:
async_mode='eventlet',

Related

pysnmp : AttributeError: 'module' object has no attribute 'NotificationOriginator'

I am working on pysnmp where my script acts as SNMP listener and forwarder. I am able to receive SNMP traps and I can see the mibs. I am getting an error with the sendPdu function of ntforg.NotificationOriginator(). I am using python 2 on centos.
here is error snippet:
Traceback (most recent call last):
File "/tmp/akhil.py", line 65, in <module>
snmp_engine.transportDispatcher.runDispatcher()
File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dispatch.py", line 50, in runDispatcher
pysnmp.error.PySnmpError: poll error: Traceback (most recent call last):
; File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dispatch.py", line 46, in runDispatcher
use_poll=True, map=self.__sockMap, count=1)
; File "/usr/lib64/python2.7/asyncore.py", line 220, in loop
poll_fun(timeout, map)
; File "/usr/lib64/python2.7/asyncore.py", line 201, in poll2
readwrite(obj, flags)
; File "/usr/lib64/python2.7/asyncore.py", line 123, in readwrite
obj.handle_error()
; File "/usr/lib64/python2.7/asyncore.py", line 108, in readwrite
obj.handle_read_event()
; File "/usr/lib64/python2.7/asyncore.py", line 449, in handle_read_event
self.handle_read()
; File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dgram/base.py", line 170, in handle_read
self._cbFun(self, transportAddress, incomingMessage)
; File "build/bdist.linux-x86_64/egg/pysnmp/carrier/base.py", line 70, in _cbFun
self, transportDomain, transportAddress, incomingMessage
; File "build/bdist.linux-x86_64/egg/pysnmp/entity/engine.py", line 152, in __receiveMessageCbFun
self, transportDomain, transportAddress, wholeMsg
; File "build/bdist.linux-x86_64/egg/pysnmp/proto/rfc3412.py", line 433, in receiveMessage
PDU, maxSizeResponseScopedPDU, stateReference)
; File "build/bdist.linux-x86_64/egg/pysnmp/entity/rfc3413/ntfrcv.py", line 115, in processPdu
contextName, varBinds, self.__cbCtx)
; File "/tmp/akhil.py", line 54, in cbFun
ntf_org = ntforg.NotificationOriginator()
;AttributeError: 'module' object has no attribute 'NotificationOriginator'
caused by <type 'exceptions.AttributeError'>: 'module' object has no attribute 'NotificationOriginator'
e here
My code :
from pysmi.codegen import PySnmpCodeGen
from pysmi.parser import SmiStarParser
from pysmi.reader import FileReader
from pysmi.searcher import PyFileSearcher, PyPackageSearcher, StubSearcher
from pysmi.writer import PyFileWriter
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.carrier.error import CarrierError
from pysnmp.entity import config, engine
from pysnmp.entity.rfc3413 import ntforg, ntfrcv
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.hlapi import *
from pysnmp.proto.api import v2c
from pysnmp.smi import builder, compiler, view
from pysnmp.smi.error import MibNotFoundError
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType
# snmpTrapAddress, SCALAR, not-accessible, IpAddress, 1.3.6.1.6.3.18.1.3.0
# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmp_engine = engine.SnmpEngine()
# UDP over IPv4
config.addTransport(
snmp_engine,
udp.domainName,
udp.UdpTransport().openServerMode(("0.0.0.0", 162))
)
config.addTransport(
snmp_engine,
udp.domainName + (2,),
udp.UdpTransport().openClientMode()
)
# SNMPv1/2c setup
config.addV1System(snmp_engine, "my-area", "public")
config.addTargetParams(snmp_engine, "distant_agent_auth", "public", "noAuthNoPriv", 1)
config.addTargetAddr(snmp_engine, "distant_agent", udp.domainName + (2,),("100.80.97.21", 162), "distant_agent_auth", retryCount=0)
def cbFun(snmp_engine, state_reference, context_engine_id, context_name, var_binds, cb_ctx):
execContext = snmp_engine.observer.getExecutionContext("rfc3412.receiveMessage:request")
trap_pdu = v2c.TrapPDU()
v2c.apiTrapPDU.setDefaults(trap_pdu)
v2c.apiTrapPDU.setVarBinds(trap_pdu, var_binds)
source_ip_address = execContext["transportAddress"][0]
print "got traps from : {}".format(source_ip_address)
var_binds_dict = {name.prettyPrint(): None if val.prettyPrint() == "" else val.prettyPrint() for name, val in var_binds}
print var_binds_dict
print "sending traps to destination 100.80.97.21"
ntf_org = ntforg.NotificationOriginator()
ntf_org.sendPdu(snmp_engine, "distant_agent", None, "", trap_pdu)
# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmp_engine, cbFun)
snmp_engine.transportDispatcher.jobStarted(1) # this job would never finish
# Run I/O dispatcher which would receive queries and send confirmations
try:
snmp_engine.transportDispatcher.runDispatcher()
except:
snmp_engine.transportDispatcher.closeDispatcher()
raise
finally:
snmp_engine.transportDispatcher.closeDispatcher()
snmp_engine.transportDispatcher.jobFinished(1)
version details :
>>> pysnmp.__version__
'4.4.9'
>>> pysmi.__version__
'0.3.4'
Am I missing anything ?
I don't know exactly 'why', but if you want to import something from hlapi try to import the specific module that you want to use. Thus avoid doing from pysnmp.hlapi import *. So if you remove that piece of code your system will probably work properly.

Error the deployment function in lambda with graphene module

error when executing the function in aws lambda, while locally there is no error.
When executing the code in AWS lambda this error arises, what I want is to be able to use graqpl to perform dynamodb queries and to use them.
Solution attempt: uninstall typing from the python virtual environment.
Error that occurs:
[ERROR] AttributeError: type object 'Callable' has no attribute '_abc_registry'
Traceback (most recent call last):
File "/var/lang/lib/python3.7/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/var/lang/lib/python3.7/imp.py", line 171, in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 696, in _load
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/var/task/patron4.py", line 7, in <module>
import graphene
File "/tmp/sls-py-req/graphene/__init__.py", line 3, in <module>
from .types import (
File "/tmp/sls-py-req/graphene/types/__init__.py", line 2, in <module>
from graphql import ResolveInfo
File "/tmp/sls-py-req/graphql/__init__.py", line 27, in <module>
from .graphql import graphql
File "/tmp/sls-py-req/graphql/graphql.py", line 1, in <module>
from .execution import ExecutionResult
File "/tmp/sls-py-req/graphql/execution/__init__.py", line 21, in <module>
from .executor import execute, subscribe
File "/tmp/sls-py-req/graphql/execution/executor.py", line 14, in <module>
from promise import Promise, promise_for_dict, is_thenable
File "/tmp/sls-py-req/promise/__init__.py", line 18, in <module>
from .promise import (
File "/tmp/sls-py-req/promise/promise.py", line 8, in <module>
from typing import (List, Any, Callable, Dict, Iterator, Optional, # flake8: noqa
File "/tmp/sls-py-req/typing.py", line 1357, in <module>
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
File "/tmp/sls-py-req/typing.py",enter code here line 1005, in __new__
self._abc_registry = extra._abc_registry
Code used:
class User(Model):
class Meta:
table_name = 'patron2'
region = 'us-east-2'
host = 'https://dynamodb.us-east-2.amazonaws.com'
id = UnicodeAttribute(hash_key=True, null=False)
discipline = UnicodeAttribute(null=False)
class UserNode(PynamoObjectType):
class Meta:
model = User
interfaces = (graphene.Node,)
class Query(graphene.ObjectType):
users = graphene.List(UserNode)
def resolve_users(self, args, context, info):
return list(User.scan())
schema = graphene.Schema(query=Query)
def patrongrafico(event, context):
# fetch all todos from the database
try:
print("hola")
query = '''
users {
discipline
}
'''
results = schema.execute(query)
print(results)
except Exception as ex:
print(ex)
return {'statusCode': 200,
'body': json.dumps({'items': [dict(result) for result in results]})}
Since you're using the Serverless Framework in combination with the serverless-python-requirements plugin you should make sure, that slim packaging is off, as this interferes with some libraries. Essentially some libraries assume they're installed via a "real" package manager and in that case the directory layout and files look slightly different.
I was having this problem with the jsonschema package a few months ago and wrote about it in a blog post if you're interested (Full disclosure: this is the blog of my employer).
Essentially your serverless.yml as a custom section which you can use among other things to configure the plugins:
custom:
pythonRequirements:
slim: true
The slim true parameter effectively removes some information that shouldn't be necessary for most libraries, but some rely on it. For information on this parameter see the package's docs.
Try again with this configuration:
custom:
pythonRequirements:
slim: false
The solution to the error is to remove the version of Python 3.7 and implement 3.6, since Graphene does not support versions greater than 3.6.

How to integrate gspread with aiohttp

I am trying to use gspread, but I need the library to mesh well with another async library I am using.
After digging through the docs for gspread, I found this function that I can use:
class gspread.Client(auth, session=None)
An instance of this class communicates with Google API.
Parameters:
auth – An OAuth2 credential object. Credential objects are those created by the oauth2client library. https://github.com/google/oauth2client
session – (optional) A session object capable of making HTTP requests while persisting some parameters across requests. Defaults to requests.Session.
Which gives me an optional session parameter. How would I specify the session to use aiohttp?
I wrote a bit of test code, which compiles fine, but running the code crashes.
import aiohttp
import gspread
import random
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
c = gspread.authorize(creds)
client = gspread.Client(auth=c, session=aiohttp.ClientSession)
sheet = client.open_by_key('1Hkwo9gSpk3NjgPLPkG8kh0zBNw2nxsYWRw0cVdn0JA0')
ws = sheet.get_worksheet(0)
rcount = ws.row_count
msg = ws.cell(random.randint(1,rcount),1).value
print(msg)
The error message I get is below:
Traceback (most recent call last):
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd_launcher.py", line 118, in <module>
vspd.debug(filename, port_num, '', '', run_as)
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\debugger.py", line 37, in debug
run(address, filename, *args, **kwargs)
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\_local.py", line 79, in run_file
run(argv, addr, **kwargs)
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\_local.py", line 140, in _run
_pydevd.main()
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\_vendored\pydevd\pydevd.py", line 1751, in main
debugger.connect(host, port)
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\_vendored\pydevd\pydevd.py", line 1107, in run
return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\_vendored\pydevd\pydevd.py", line 1114, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "c:\Users\xxxxx\.vscode\extensions\ms-python.python-2018.9.0\pythonFiles\experimental\ptvsd\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "c:\Users\xxxxx\Desktop\Coding\Discord Bot\Testing\test.py", line 14, in <module>
ws = sheet.get_worksheet(0)
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\site-packages\gspread\models.py", line 141, in get_worksheet
sheet_data = self.fetch_sheet_metadata()
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\site-packages\gspread\models.py", line 123, in fetch_sheet_metadata
r = self.client.request('get', url, params=params)
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python36\lib\site-packages\gspread\client.py", line 73, in request
headers=headers
TypeError: get() missing 1 required positional argument: 'url'
PS C:\Users\xxxxx\Desktop\Coding\Discord Bot>
Any ideas?
It's impossible to use aiohttp with current version of gspread (3.0.1). the gspread library uses synchronous calls and aiohttp uses asynchronous calls.
Please, reconsider to use compatible library like requests or httplib2.
For anyone wondering, once I posted this question, I found that someone made an async wrapper for gspread. Check out the library here and show this guy your appreciation. I sure am!

werkzeug server failed to handle request

I'm trying to run this gevent server
from gevent import pywsgi
from Index import application
import paste.urlparser
import os
# http server: serves up static files
print "static files",os.path.dirname(__file__)
print "serving on localhost:8000"
http_server = pywsgi.WSGIServer(
('', 8000),
paste.urlparser.StaticURLParser(os.path.dirname(__file__)))
print 'Serving on https://127.0.0.1:4000'
server = pywsgi.WSGIServer(('0.0.0.0', 4000), application,spawn=None)
# Start the server greenlets
http_server.start()
# to start the server asynchronously, call server.start()
# we use blocking serve_forever() here because we have no other jobs
server.serve_forever()
I'm getting this exception where it gives me failed to handle request from werkzeug server.
I've used only werkzeug utility and have never used werkzeug server..
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 131, in _do_accept
self._handle(client_socket, address)
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 571, in handle
handler.handle()
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 180, in handle
result = self.handle_one_request()
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 287, in handle_one_request
raw_requestline = self.read_requestline()
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 280, in read_requestline
return self.rfile.readline(MAX_REQUEST_LINE)
File "/usr/lib/python2.7/socket.py", line 476, in readline
data = self._sock.recv(self._rbufsize)
File "/usr/local/lib/python2.7/dist-packages/gevent/socket.py", line 432, in recv
wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
File "/usr/local/lib/python2.7/dist-packages/gevent/socket.py", line 169, in wait_read
switch_result = get_hub().switch()
File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 154, in switch
assert cur is not self, 'Cannot switch to MAINLOOP from MAINLOOP'
AssertionError: Cannot switch to MAINLOOP from MAINLOOP
<WSGIServer fileno=4 address=0.0.0.0:4000>: Failed to handle request from ('127.0.0.1', 36088)

Error 1053 When Starting Window Service Written In Python

I have already looked at and tried the resolutions to this question that others have posted. One user said that to try and change my setup.py file from:
from distutils.core import setup
import py2exe
setup(console=["dev.py"])
to
from distutils.core import setup
import py2exe
setup(service=["dev.py"])
I got the following results:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "C:\Python27\Scripts\distutils-setup.py", line 5, in <module>
setup(service=["C:\Python27\Scripts\dev.py"])
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1274, in
find_needed_modules
mf.import_hook(mod)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named dev
Now, when I run py2exe with "console" in my setup script it works fine, but the service doesn't start and I get the error. When I run py2exe with "service" in my setup script py2exe doesn't run and tells me it can't find my module.
I have tried to re-install py2exe to no resolution. I have also tried to change:
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
to
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Didn't make a difference either. CAN ANYONE HELP ME PLEASE? Here is what I am working on. It monitors a server and spits back a text file every 60 seconds which I use to monitor my servers at any given minute. Any help you guys and gals can give would be great.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import wmi
import _winreg
from time import sleep
import os
class SrvMonSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "SrvMonSvc"
_svc_display_name_ = "Server Monitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
host = wmi.WMI(namespace="root/default").StdRegProv
try:
result, api = host.GetStringValue(
hDefKey = _winreg.HKEY_LOCAL_MACHINE,
sSubKeyName = "SOFTWARE\Server Monitor",
sValueName = "API")
if api == None:
raise Exception
else:
pass
except:
exit()
while 1 == 1:
with open("C:/test.txt", "wb") as b:
computer = wmi.WMI(computer="exsan100")
for disk in computer.Win32_LogicalDisk (DriveType=3):
name = disk.caption
size = round(float(disk.Size)/1073741824, 2)
free = round(float(disk.FreeSpace)/1073741824, 2)
used = round(float(size), 2) - round(float(free), 2)
for mem in computer.Win32_OperatingSystem():
a_mem = (int(mem.FreePhysicalMemory)/1024)
for me in computer.Win32_ComputerSystem():
t_mem = (int(me.TotalPhysicalMemory)/1048576)
u_mem = t_mem - a_mem
for cpu in computer.Win32_Processor():
load = cpu.LoadPercentage
print >>b, api
print >>b, name
print >>b, size
print >>b, used
print >>b, t_mem
print >>b, u_mem
print >>b, load
b.close()
date_list = []
stamp = time.strftime("%c",time.localtime(time.time()))
date_list.append(stamp)
name = re.sub(r"[^\w\s]", "",date_list[0])
os.rename("C:/test.txt", ("C:/%s.txt" % name))
try:
sleep(60.00)
except:
exit()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SrvMonSvc)
Have you progressed from your original problem. I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete.
Running pythonservice.exe with -debug from the command prompt was not a problem because it used correct PATH environment variable, but if your service is installed as a System service it's worth checking out if the System Path variable has all the paths for the required DLLs (MSVC, Python, System32). For me it was missing the python DLLs path, after that it worked again.

Resources