Python: Code crashes randomly when checking e-mail - python

This code:
import imaplib, re
import os
import time
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("ddd#ddd.com", "ddd")
while(True):
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
print unreadCount
if int(unreadCount) > 20:
os.system('heroku restart --app warm-beach-203')
#os.system('ls')
#print "Restarting server...."
time.sleep(60)
Output:
0
1
0
0
0
0
0
4
Traceback (most recent call last):
File "gmail.py", line 10, in <module>
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 704, in status
typ, dat = self._simple_command(name, mailbox, names)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 1059, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 889, in _command_complete
typ, data = self._get_tagged_response(tag)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 990, in _get_tagged_response
self._get_response()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 907, in _get_response
resp = self._get_line()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 1000, in _get_line
line = self.readline()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 1170, in readline
char = self.sslobj.read(1)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ssl.py", line 136, in read
return self._sslobj.read(len)
socket.error: [Errno 60] Operation timed out
I dont understand why it crashes randomly.

The final error line is descriptive: the connection is timing out before the IMAP operation completes. It could be simply that Gmail is running slowly. If that's the case, you could try extending the timeout like so:
import socket
socket.setdefaulttimeout(15) # In seconds
where 15 is the value you've experimentally determined works well for you.

Related

httpx.ReadTimeout on Range filter on Supabase-py

I have 375000 items in my table.
I am doing a loop to obtain all id of all items, with API limit set to 20000 items per api call.
After 200000 I always start to get httpx.ReadTimeout: The read operation timed out sometime it may reach 240000 but never go ahead.
I have tried to have different wait time after each loop.
I have tried to change api limit to 10000 as well as increase it to 30000 or 50000 make less calls but in all cases it get's stuck at around 150000 or 200000.
existing_search_result = supabase.table('vehicles').select('ref_id', count='exact').order('id', desc=False).execute()
existing_items = []
range_step = len(existing_search_result.data)
total_existing_items = existing_search_result.count
print(total_existing_items)
while len(existing_items) < total_existing_items:
try:
existing_items += (
supabase.table(
'vehicles'
).select('ref_id')
.order('id', desc=False)
.range(range_start, range_start + range_step)
.execute()
).data
range_start += range_step
except Exception as e:
logging.exception(e)
print(range_start, len(existing_items))
time.sleep(0.30)
Error log:
2022-10-23 21:04:14,168:ERROR - The read operation timed out
Traceback (most recent call last):
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_exceptions.py", line 8, in map_exceptions
yield
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/backends/sync.py", line 26, in read
return self._sock.recv(max_bytes)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/ssl.py", line 1226, in recv
return self.read(buflen)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/ssl.py", line 1101, in read
return self._sslobj.read(len)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 60, in map_httpcore_exceptions
yield
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 204, in handle_request
resp = self._pool.handle_request(req)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/connection_pool.py", line 253, in handle_request
raise exc
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/connection_pool.py", line 237, in handle_request
response = connection.handle_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/connection.py", line 90, in handle_request
return self._connection.handle_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 102, in handle_request
raise exc
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 81, in handle_request
) = self._receive_response_headers(**kwargs)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 143, in _receive_response_headers
event = self._receive_event(timeout=timeout)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_sync/http11.py", line 172, in _receive_event
data = self._network_stream.read(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/backends/sync.py", line 26, in read
return self._sock.recv(max_bytes)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/contextlib.py", line 135, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpcore/_exceptions.py", line 12, in map_exceptions
raise to_exc(exc)
httpcore.ReadTimeout: The read operation timed out
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/ak4zh/updater/main.py", line 278, in job
supabase.table(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/postgrest/_sync/request_builder.py", line 53, in execute
r = self.session.request(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 802, in request
return self.send(request, auth=auth, follow_redirects=follow_redirects)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 889, in send
response = self._send_handling_auth(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 917, in _send_handling_auth
response = self._send_handling_redirects(
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 954, in _send_handling_redirects
response = self._send_single_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_client.py", line 990, in _send_single_request
response = transport.handle_request(request)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 204, in handle_request
resp = self._pool.handle_request(req)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/contextlib.py", line 135, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/ak4zh/updater/venv/lib/python3.9/site-packages/httpx/_transports/default.py", line 77, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.ReadTimeout: The read operation timed out
I had the same problem, so I create a function to get 1000 item and merge it!
this is my code:
def count_data(tb_name: str, field_name: str):
return supabase.table(tb_name).select(field_name, count='exact').execute().count
def get_field_data(tb_name: str, src_field: str, len_record: int, id_field: str = 'id'):
if len_record <= 1000:
field_data = supabase.table(tb_name).select(id_field, src_field).order(
column=id_field).execute().data
else:
rnk = int(len_record / 1000)
field_data = []
for i in range(rnk):
min_rg = (i * 1000) + 1
max_rg = (i + 1) * 1000
field_data = field_data + supabase.table(tb_name).select(id_field, src_field).order(
column=id_field).range(min_rg - 1, max_rg).execute().data
field_data = field_data + supabase.table(tb_name).select(id_field, src_field).order(
column=id_field).range(max_rg, len_record).execute().data
return field_data

Autokey: sporadic error on system.exec_command

I have a script that grabs the window title and writes out a debug statement based on whether the file title includes a certain string.
active_title = window.get_active_title()
counter = system.exec_command("date '+%s'")
newcounter = counter[-5:]
counter = newcounter
time.sleep(.4)
if '.php' in active_title:
output = "die('<pre>[" + str(counter) + "] ' . date('Y-m-d H:i:s'));"
time.sleep(.2)
clipboard.fill_clipboard(output)
time.sleep(.2)
keyboard.send_keys('<ctrl>+v')
if '.js' in active_title:
output = "console.log('[" + str(counter) + "] ' + Date.now())"
time.sleep(.2)
clipboard.fill_clipboard(output)
time.sleep(.2)
keyboard.send_keys('<ctrl>+v')
time.sleep(.2)
keyboard.send_keys("<ctrl>+s")
99% of the time it works without issue, but that 100th time it throws this error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/service.py", line 485, in execute
exec(script.code, scope)
File "<string>", line 2, in <module>
File "/usr/lib/python3/dist-packages/autokey/scripting.py", line 1104, in get_active_title
return self.mediator.interface.get_window_title()
File "/usr/lib/python3/dist-packages/autokey/interface.py", line 1158, in get_window_title
return self.get_window_info(window, traverse).wm_title
File "/usr/lib/python3/dist-packages/autokey/interface.py", line 1074, in get_window_info
return self._get_window_info(window, traverse)
File "/usr/lib/python3/dist-packages/autokey/interface.py", line 1081, in _get_window_info
new_wm_class = self._try_get_window_class(window)
File "/usr/lib/python3/dist-packages/autokey/interface.py", line 1151, in _try_get_window_class
wm_class = window.get_wm_class()
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/xobject/drawable.py", line 660, in get_wm_class
d = self.get_full_property(Xatom.WM_CLASS, Xatom.STRING)
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/xobject/drawable.py", line 452, in get_full_property
prop = self.get_property(property, type, 0, sizehint)
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/xobject/drawable.py", line 435, in get_property
r = request.GetProperty(display = self.display,
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/protocol/rq.py", line 1481, in __init__
self.reply()
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/protocol/rq.py", line 1493, in reply
self._display.send_and_recv(request = self._serial)
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/protocol/display.py", line 556, in send_and_recv
gotreq = self.parse_response(request)
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/protocol/display.py", line 643, in parse_response
gotreq = self.parse_request_response(request) or gotreq
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/protocol/display.py", line 720, in parse_request_response
req = self.get_waiting_replyrequest()
File "/home/seamlyne/.local/lib/python3.9/site-packages/Xlib/protocol/display.py", line 847, in get_waiting_replyrequest
raise RuntimeError("Request reply to unknown request. Can't happen!")
RuntimeError: Request reply to unknown request. Can't happen!
Closing and restarting Autokey helps, but I'd like to avoid the error if at all possible. I have several scripts that get the window title, and this is the only script that has this issue. Is there something wrong with using system.exec_command?
Since you are invoking the clipboard, it helps to add to the start and the end
os.system("sleep .1; xsel -cb")
to clear it.

Issues with Odoo v13 UID/API

Having an issue with the api for Odoo v13. I am able to get the server info but for some reason the uid is not being returned
import xmlrpc.client
url ="localhost:8069"
db = "pnv3"
username = "test"
password = "test"
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
print(common.version())
uid = common.authenticate(db, username, password, url)
print(uid)
getting this error
Traceback (most recent call last):
File "C:/Users/Web Content/.PyCharmCE2019.3/config/scratches/scratch.py", line 11, in <module>
uid = common.authenticate(db, username, password, url)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1452, in __request
verbose=self.__verbose
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1170, in single_request
return self.parse_response(resp)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1342, in parse_response
return u.close()
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 656, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 1: 'Traceback (most recent call last):\n File "/odoo/odoo-server/odoo/modules/registry.py", line 59, in __new__\n return cls.registries[db_name]\n File "/odoo/odoo-server/odoo/tools/func.py", line 69, in wrapper\n return func(self, *args, **kwargs)\n File "/odoo/odoo-server/odoo/tools/lru.py", line 44, in __getitem__\n a = self.d[obj].me\nKeyError: \'pnv3\'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File "/odoo/odoo-server/odoo/addons/base/controllers/rpc.py", line 63, in xmlrpc_2\n response = self._xmlrpc(service)\n File "/odoo/odoo-server/odoo/addons/base/controllers/rpc.py", line 43, in _xmlrpc\n result = dispatch_rpc(service, method, params)\n File "/odoo/odoo-server/odoo/http.py", line 138, in dispatch_rpc\n result = dispatch(method, params)\n File "/odoo/odoo-server/odoo/service/common.py", line 61, in dispatch\n return g[exp_method_name](*params)\n File "/odoo/odoo-server/odoo/service/common.py", line 30, in exp_authenticate\n res_users = odoo.registry(db)[\'res.users\']\n File "/odoo/odoo-server/odoo/__init__.py", line 104, in registry\n return modules.registry.Registry(database_name)\n File "/odoo/odoo-server/odoo/modules/registry.py", line 61, in __new__\n return cls.new(db_name)\n File "/odoo/odoo-server/odoo/modules/registry.py", line 73, in new\n registry.init(db_name)\n File "/odoo/odoo-server/odoo/modules/registry.py", line 141, in init\n with closing(self.cursor()) as cr:\n File "/odoo/odoo-server/odoo/modules/registry.py", line 492, in cursor\n return self._db.cursor()\n File "/odoo/odoo-server/odoo/sql_db.py", line 649, in cursor\n return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)\n File "/odoo/odoo-server/odoo/sql_db.py", line 186, in __init__\n self._cnx = pool.borrow(dsn)\n File "/odoo/odoo-server/odoo/sql_db.py", line 532, in _locked\n return fun(self, *args, **kwargs)\n File "/odoo/odoo-server/odoo/sql_db.py", line 600, in borrow\n **connection_info)\n File "/usr/local/lib/python3.7/dist-packages/psycopg2/__init__.py", line 130, in connect\n conn = _connect(dsn, connection_factory=connection_factory, **kwasync)\npsycopg2.OperationalError: FATAL: database "pnv3" does not exist\n\n'>
Process finished with exit cod
1
Databse does exist, have triple checked my password, not sure what else to do at this point.
The url to Odoo server should include protocol part "http://" in the beginning. Strange that you get the version info at all. What do you get as output for the version?
Also you pass the url as the last parameter to authenticate method and this is not required. This should still not give the error you received.
Try your code with these two fixes and report if this helps:
import xmlrpc.client
url ="http://localhost:8069"
db = "pnv3"
username = "test"
password = "test"
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
print(common.version())
uid = common.authenticate(db, username, password, {})
print(uid)
Identical code works on my machine...

How to write a DownloadHandler for scrapy that makes socks4 requests through txsocksx

I am working on a college project, but I need to make the code below work with socks4 instead of tor/socks5. I have tried modifying SOCKS5Agent to SOCKS4Agent but then I receive and error:
Original code: https://stackoverflow.com/a/33944924/11219616
My code:
import scrapy.core.downloader.handlers.http11 as handler
from twisted.internet import reactor
from txsocksx.http import SOCKS4Agent
from twisted.internet.endpoints import TCP4ClientEndpoint
from scrapy.core.downloader.webclient import _parse
class TorScrapyAgent(handler.ScrapyAgent):
_Agent = SOCKS4Agent
def _get_agent(self, request, timeout):
proxy = request.meta.get('proxy')
if proxy:
proxy_scheme, _, proxy_host, proxy_port, _ = _parse(proxy)
if proxy_scheme == 'socks4':
endpoint = TCP4ClientEndpoint(reactor, proxy_host, proxy_port)
return self._Agent(reactor, proxyEndpoint=endpoint)
return super(TorScrapyAgent, self)._get_agent(request, timeout)
class TorHTTPDownloadHandler(handler.HTTP11DownloadHandler):
def download_request(self, request, spider):
agent = TorScrapyAgent(contextFactory=self._contextFactory, pool=self._pool,
maxsize=getattr(spider, 'download_maxsize', self._default_maxsize),
warnsize=getattr(spider, 'download_warnsize', self._default_warnsize))
return agent.download_request(request)
I get the error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\internet\defer.py", line 1416, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "C:\Python27\lib\site-packages\twisted\python\failure.py", line 491, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "C:\Python27\lib\site-packages\scrapy\core\downloader\middleware.py", line 43, in process_request
defer.returnValue((yield download_func(request=request,spider=spider)))
File "C:\Python27\lib\site-packages\ometa\protocol.py", line 53, in dataReceived
self._parser.receive(data)
File "C:\Python27\lib\site-packages\ometa\tube.py", line 41, in receive
status = self._interp.receive(data)
File "C:\Python27\lib\site-packages\ometa\interp.py", line 48, in receive
for x in self.next:
File "C:\Python27\lib\site-packages\ometa\interp.py", line 177, in apply
for x in self._apply(f, ruleName, argvals):
File "C:\Python27\lib\site-packages\ometa\interp.py", line 110, in _apply
for x in rule():
File "C:\Python27\lib\site-packages\ometa\interp.py", line 256, in parse_Or
for x in self._eval(subexpr):
File "C:\Python27\lib\site-packages\ometa\interp.py", line 241, in parse_And
for x in self._eval(subexpr):
File "C:\Python27\lib\site-packages\ometa\interp.py", line 440, in parse_Action
val = eval(expr.data, self.globals, self._localsStack[-1])
File "<string>", line 1, in <module>
File "C:\Python27\lib\site-packages\txsocksx\client.py", line 276, in serverResponse
raise e.socks4ErrorMap.get(status)()
RequestRejectedOrFailed

Logging exception error upgrading to python 3.4 from python 2.7

My application was running well but as I upgraded it to python version 3.4 . I am getting the error shown bellow. Looking at the error message I am not exactly able to debug the problem
Error:
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib64/python3.4/logging/__init__.py", line 978, in emit
msg = self.format(record)
File "/usr/lib64/python3.4/logging/__init__.py", line 828, in format
return fmt.format(record)
File "/usr/lib64/python3.4/logging/__init__.py", line 573, in format
record.exc_text = self.formatException(record.exc_info)
File "/usr/lib64/python3.4/logging/__init__.py", line 523, in formatException
traceback.print_exception(ei[0], ei[1], tb, None, sio)
File "/usr/lib64/python3.4/traceback.py", line 169, in print_exception
for line in _format_exception_iter(etype, value, tb, limit, chain):
File "/usr/lib64/python3.4/traceback.py", line 146, in _format_exception_iter
for value, tb in values:
File "/usr/lib64/python3.4/traceback.py", line 125, in _iter_chain
context = exc.__context__
AttributeError: 'NoneType' object has no attribute '__context__'
Call stack:
File "main.py", line 253, in <module>
main()
File "main.py", line 144, in main
plugininfo.plugin_object.run(cons.MAIN_CONFIG_PATH, outputpath, finallogs, plugininfo.name, args.inventory)
File "/home/sjoshi/python3.4/check-acess/plugins/plugin_etc_passwd/plugin_etc_passwd.py", line 107, in run
self.result = phelper.executeCommand(runcommand)
File "/home/sjoshi/python3.4/check-acess/lib/sshplugin/sshplugin.py", line 86, in executeCommand
logging.exception("ErrorCode:%d %s", cmdout.returncode, output)
Message: 'ErrorCode:%d %s'
Arguments: (255, b'')
No Result found or all users filtered sbx32 /etc/passwd
Permission denied (publickey).
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib64/python3.4/logging/__init__.py", line 978, in emit
msg = self.format(record)
File "/usr/lib64/python3.4/logging/__init__.py", line 828, in format
return fmt.format(record)
File "/usr/lib64/python3.4/logging/__init__.py", line 573, in format
record.exc_text = self.formatException(record.exc_info)
File "/usr/lib64/python3.4/logging/__init__.py", line 523, in formatException
traceback.print_exception(ei[0], ei[1], tb, None, sio)
File "/usr/lib64/python3.4/traceback.py", line 169, in print_exception
for line in _format_exception_iter(etype, value, tb, limit, chain):
File "/usr/lib64/python3.4/traceback.py", line 146, in _format_exception_iter
for value, tb in values:
File "/usr/lib64/python3.4/traceback.py", line 125, in _iter_chain
context = exc.__context__
AttributeError: 'NoneType' object has no attribute '__context__'
Call stack:
File "main.py", line 253, in <module>
main()
File "main.py", line 144, in main
plugininfo.plugin_object.run(cons.MAIN_CONFIG_PATH, outputpath, finallogs, plugininfo.name, args.inventory)
File "/home/sjoshi/python3.4/check-acess/plugins/plugin_etc_passwd/plugin_etc_passwd.py", line 107, in run
self.result = phelper.executeCommand(runcommand)
File "/home/sjoshi/python3.4/check-acess/lib/sshplugin/sshplugin.py", line 86, in executeCommand
logging.exception("ErrorCode:%d %s", cmdout.returncode, output)
Message: 'ErrorCode:%d %s'
Arguments: (255, b'')
sshplugin.py
import os
import subprocess as subp
import logging
import lib.exceptions.errors as error
import lib.inventory.bashhostlist as hostname
class SSHPlugin:
"""
Helper class for the SSH based plugins
"""
def makeCommand(self, user, host, filepath, sudo, timeout, attempt, changetols=None):
"""
-Two types of commands with or without ssh depends on hostname
-Other depends on parameter set or unset
-ConnectionAttempts and ConnectTimeout to occur must be SSH
-last arg(changetols): This is to checkif the plugin type is authorized_keys. Because in that case we need ls not cat
"""
command=""
if changetols is None:
command = ["cat", filepath]
else:
command=["ls", filepath]
if host.lower() == 'localhost':
if sudo.lower() == 'yes':
command.insert(0, 'sudo')
else:
command.insert(0, "ssh")
if timeout and not attempt:
command.insert(1, '-o')
command.insert(
2, "ConnectTimeout={timeout}".format(timeout=timeout))
command.insert(3, user+"#"+host)
if sudo.lower() == 'yes':
command.insert(4, 'sudo')
elif timeout and attempt:
command.insert(1, '-o')
command.insert(
2, "ConnectTimeout={timeout}".format(timeout=timeout))
command.insert(3, '-o')
command.insert(
4, "ConnectionAttempts={att}".format(att=attempt))
command.insert(5, user+"#"+host)
if sudo.lower() == 'yes':
command.insert(6, 'sudo')
elif attempt and not timeout:
command.insert(1, '-o')
command.insert(
2, "ConnectionAttempts={att}".format(att=attempt))
command.insert(3, user+"#"+host)
if sudo.lower() == 'yes':
command.insert(4, 'sudo')
else:
command.insert(1, user+"#"+host)
if sudo.lower() == 'yes':
command.insert(2, 'sudo')
return command
def executeCommand(self, command, filtercommand=None):
"""
Multuple Popen used to execute the process,Command followed by filter if any
if no filter than just a single commad run else
The output of first will act as the input to the filtering command
"""
if filtercommand is None:
cmdout = subp.Popen(command, stdout=subp.PIPE)
output, err = cmdout.communicate()
if cmdout.returncode is 0:
logging.info("Result success,status code %d", cmdout.returncode)
return output
else:
logging.exception("ErrorCode:%d %s %s", cmdout.returncode, output,err)
return False
else:
cmdout = subp.Popen(command, stdout=subp.PIPE)
filtered = subp.Popen(filtercommand, stdin=cmdout.stdout, stdout=subp.PIPE)
output, err = filtered.communicate()
if filtered.returncode is 0:
logging.info("Result success,status code %d", filtered.returncode)
return output
else:
logging.exception("ErrorCode:%d %s", filtered.returncode, output)
return False
why is the logging.exception throwing errors. Is it the problem with the logging module. I tried to replace the logging.exception with logging.info instead but that didn't work.

Categories

Resources