I'm trying to write a program to take screen cap using a global hot key. Below is the corresponding code:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
Error Message:
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
return f(self, *args, **kwargs)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process self.on_press(key)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
if f(*args) is False:
File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
return lambda k: f(l.canonical(k))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
self._on_activate()
File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save
format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/PycharmProjects/untitled1/123.py", line 26, in <module>
l.join()
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 259, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\six.py", line 702, in reraise
raise value.with_traceback(tb)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
return f(self, *args, **kwargs)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
self.on_press(key)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
if f(*args) is False:
File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
return lambda k: f(l.canonical(k))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
self._on_activate()
File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
I do not know how to save the image to the folder. I expect the code below will not work this:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
Changing the function to on_activate with a simple action such as:
Print("Hello")
The hotkey script works perfectly.
I am new to programming, so any help is appreciated!
Here the fixed code:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
The problem was that you were using:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
The function pathlib.Path(fpath,d,".jpg") join the string adding the \ to the end of each, so the path where you are trying to save the file is:
C:Users\Desktop\TestScreenCap\200309\2020-09-03-16-50-20\.jpg
As you can see the filename is the extension, that throw the exception.
Just replace with this: myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
Another problem on the specified path is that C: is interpreted as Drive, so when you save the function, is saved to the path where your program is currently running, not at the real specified path. To fix this part, just replace C: with C:\\.
Reading your code I think you would like to save the screenshot in the current user Desktop, if so replace the line: fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp) with fpath = pathlib.Path(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'), time_stamp) and just add on the top the import os. With this you don't need to care about the right generation for the path.
Related
I`m trying to download and then open excel file (report) generated by marketplace with openpyxl.
import requests
import config
import openpyxl
link = 'https://api.telegram.org/file/bot' + config.TOKEN + '/documents/file_66.xlsx'
def save_open(link):
filename = link.split('/')[-1]
r = requests.get(link)
with open(filename, 'wb') as new_file:
new_file.write(r.content)
wb = openpyxl.open ('file_66.xlsx')
ws = wb.active
cell = ws['B2'].value
print (cell)
save_open(link)
After running this code I got the above:
Traceback (most recent call last):
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\base.py", line 55, in _convert
value = expected_type(value)
TypeError: Fill() takes no arguments
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Home\Documents\myPython\bot_WB\main.py", line 20, in <module>
save_open(link)
File "C:\Users\Home\Documents\myPython\bot_WB\main.py", line 14, in save_open
wb = openpyxl.open ('file_66.xlsx')
File "C:\Python 3.9\lib\site-packages\openpyxl\reader\excel.py", line 317, in load_workbook
reader.read()
File "C:\Python 3.9\lib\site-packages\openpyxl\reader\excel.py", line 281, in read
apply_stylesheet(self.archive, self.wb)
File "C:\Python 3.9\lib\site-packages\openpyxl\styles\stylesheet.py", line 198, in apply_stylesheet
stylesheet = Stylesheet.from_tree(node)
File "C:\Python 3.9\lib\site-packages\openpyxl\styles\stylesheet.py", line 103, in from_tree
return super(Stylesheet, cls).from_tree(node)
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
return cls(**attrib)
File "C:\Python 3.9\lib\site-packages\openpyxl\styles\stylesheet.py", line 74, in __init__
self.fills = fills
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\sequence.py", line 26, in __set__
seq = [_convert(self.expected_type, value) for value in seq]
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\sequence.py", line 26, in <listcomp>
seq = [_convert(self.expected_type, value) for value in seq]
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\base.py", line 57, in _convert
raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'openpyxl.styles.fills.Fill'>
[Finished in 1.6s]
If you run file properties/details you can see that this file was generated by "Go Exelize" (author: xuri). To run this file you need to separate code in two parts. First: download file. Then you need to manually open it with MS Excel, save file and close it (after this "Go Excelize" switch to "Microsoft Excel"). And only after that you can run the second part of the code correctly with no errors. Can anyone help me to handle this problem?
I had the same problem, "TypeError('expected ' + str(expected_type))", using pandas.read_excel, which uses openpyxl. If I open the file, save and close it, it will work with both, pandas and openpyxl.
Upon further attempts I could open the file using the "read_only=True" in openpyxl, but while iterating over the rows I would still get the error, but only when all the rows ended, in the end of the file.
I belive it could be something in the EOF (end of file) and openpyxl don't have ways of treating it.
Here is the code that I used to test and worked for me:
import openpyxl
wb = openpyxl.load_workbook(my_file_name, read_only=True)
ws = wb.worksheets[0]
lis = []
try:
for row in ws.iter_rows():
lis.append([cell.value for cell in row])
except TypeError:
print('Skip error in EOF')
Used openpyxl==3.0.10
I have been trying to make some graphs in pyqt5 that can update more quickly and efficiently than my currently embedded matplotlib ones.
I keep running into the same problem whenever I run any example code including pyqtgraph, which always throw the following error:
"TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget"
Environment:
Spyder 3.3.2 Python 3.7.1 64-bit | Qt 5.9.6 | PyQt5 5.9.2 | Windows 10.
After running pip freeze I learned my versions are numpy==1.20.1, PyQt5==5.15.2, PyQt5-sip==12.8.1, pyqtgraph==0.11.1
I'm using a very simple test graph from a turial (Link).
from PyQt5 import QtWidgets
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys # We need sys so that we can pass argv to QApplication
import os
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.graphWidget = pg.PlotWidget()
self.setCentralWidget(self.graphWidget)
hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [30,32,34,32,33,31,29,32,35,45]
# plot data: x, y values
self.graphWidget.plot(hour, temperature)
def main():
app = QtWidgets.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The code which causes the error most recent in traceback is in "Qt.py", in the following code:
# Common to PyQt4 and 5
if QT_LIB in [PYQT4, PYQT5]:
QtVersion = QtCore.QT_VERSION_STR
try:
from PyQt5 import sip
except ImportError:
import sip
def isQObjectAlive(obj):
return not sip.isdeleted(obj)
loadUiType = uic.loadUiType
QtCore.Signal = QtCore.pyqtSignal
The full traceback is much longer, and is as follows:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not PlotItem
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 438, in resizeEvent
self.updateAutoRange()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 890, in updateAutoRange
childRange = self.childrenBounds(frac=fractionVisible)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 1355, in childrenBounds
px, py = [v.length() if v is not None else 0 for v in self.childGroup.pixelVectors()]
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 189, in pixelVectors
dt = self.deviceTransform()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 108, in deviceTransform
view = self.getViewWidget()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 65, in getViewWidget
if v is not None and not isQObjectAlive(v):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\Qt.py", line 328, in isQObjectAlive
return not sip.isdeleted(obj)
TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not PlotDataItem
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not PlotDataItem
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 26, in itemChange
self.parentChanged()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 463, in parentChanged
self._updateView()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 480, in _updateView
view = self.getViewBox()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 88, in getViewBox
vb = self.getViewWidget()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 65, in getViewWidget
if v is not None and not isQObjectAlive(v):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\Qt.py", line 328, in isQObjectAlive
return not sip.isdeleted(obj)
TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not ChildGroup
Traceback (most recent call last):
File "<ipython-input-2-5f5dea77ec5e>", line 1, in <module>
runfile('C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py', wdir='C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py", line 30, in <module>
main()
File "C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py", line 24, in main
main = MainWindow()
File "C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py", line 19, in __init__
self.graphWidget.plot(hour, temperature)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 653, in plot
self.addItem(item, params=params)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 530, in addItem
self.vb.addItem(item, *args, **vbargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 409, in addItem
self.updateAutoRange()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 890, in updateAutoRange
childRange = self.childrenBounds(frac=fractionVisible)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 1355, in childrenBounds
px, py = [v.length() if v is not None else 0 for v in self.childGroup.pixelVectors()]
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 189, in pixelVectors
dt = self.deviceTransform()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 108, in deviceTransform
view = self.getViewWidget()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 65, in getViewWidget
if v is not None and not isQObjectAlive(v):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\Qt.py", line 328, in isQObjectAlive
return not sip.isdeleted(obj)
TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget
def getFile():
global filename, path, path2
filename = QtWidgets.QFileDialog.getOpenFileName()[0]
path = filename
print(path)
I think the problem is in this function
def getTo():
wb = load_workbook(filename = filename)
and there is mising some settings in filename functon,
i tried using unicode, but it doesnt solve the problem
Traceback (most recent call last):
File "C:/Users/pro10/PycharmProjects/Program/gui5.py", line 118, in getTo
sheet['A' + str(rows)] = text1
File "C:\Users\pro10\PycharmProjects\pythonProject\venv\lib\site-packages\openpyxl\worksheet\worksheet.py", line 313, in __setitem__
self[key].value = value
File "C:\Users\pro10\PycharmProjects\pythonProject\venv\lib\site-packages\openpyxl\cell\cell.py", line 216, in value
self._bind_value(value)
File "C:\Users\pro10\PycharmProjects\pythonProject\venv\lib\site-packages\openpyxl\cell\cell.py", line 199, in _bind_value
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert <function text1 at 0x0000023DFE3D3A60> to Excel
Did you import the load_workbook function, like this?
from openpyxl import load_workbook
I am trying out AWS Neptune for the first time using Chalice.
This is the entire error
Traceback (most recent call last):
File "/var/task/chalice/app.py", line 1104, in _get_view_function_response
response = view_function(**function_args)
File "/var/task/app.py", line 44, in getPosts
raise e
File "/var/task/app.py", line 37, in getPosts
result = g.V().has('name', 'test1').toList()
File "/var/task/gremlin_python/process/traversal.py", line 58, in toList
return list(iter(self))
File "/var/task/gremlin_python/process/traversal.py", line 48, in __next__
self.traversal_strategies.apply_strategies(self)
File "/var/task/gremlin_python/process/traversal.py", line 573, in apply_strategies
traversal_strategy.apply(traversal)
File "/var/task/gremlin_python/driver/remote_connection.py", line 149, in apply
remote_traversal = self.remote_connection.submit(traversal.bytecode)
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 55, in submit
result_set = self._client.submit(bytecode)
File "/var/task/gremlin_python/driver/client.py", line 111, in submit
return self.submitAsync(message, bindings=bindings).result()
File "/var/task/gremlin_python/driver/client.py", line 127, in submitAsync
return conn.write(message)
File "/var/task/gremlin_python/driver/connection.py", line 55, in write
self.connect()
File "/var/task/gremlin_python/driver/connection.py", line 45, in connect
self._transport.connect(self._url, self._headers)
File "/var/task/gremlin_python/driver/tornado/transport.py", line 36, in connect
lambda: websocket.websocket_connect(url))
File "/var/task/tornado/ioloop.py", line 576, in run_sync
return future_cell[0].result()
tornado.simple_httpclient.HTTPStreamClosedError: Stream closed
and here is my code
import logging
from chalice import Chalice, BadRequestError, NotFoundError
from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.process.traversal import T, P, Operator
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from datetime import datetime
app = Chalice(app_name='chalice-neptune')
app.debug = True
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
def setup_graph():
try:
graph = Graph()
connstring = 'ws://NEPTUNE-ENDPOINT-HERE:8182/gremlin'
g = graph.traversal().withRemote(DriverRemoteConnection(connstring, 'g'))
logging.info('Connected to Neptune')
except Exception as e:
logging.error(e, exc_info = True)
raise BadRequestError("Could not connect to Neptune")
return g
#app.route('/getPosts')
def getPosts():
g = setup_graph()
try:
result = g.V().has('name', 'test1').toList()
response = {
'status_code': 200,
'data': result
}
except Exception as e:
raise e
return response
Any one who have tried this?
I have followed the example found in this bucket gremlin-python-example
I know I have not missed anything from the example but it is still throwing stream closed error.
Apparently the only thing I changed was my connection string and it is now working fine.
connstring = 'wss://NEPTUNE-ENDPOINT-HERE:8182/gremlin'
I changed it from ws to wss.
As to the difference between the two you can refer to this answer
Difference between ws and wss?
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.