How do I compare two python scripts with the difflib library? - python-3.x

I want to compare two python scripts with the difflib library.
One of the scripts is working, the other one is not.
I used the following code to compare the two files:
import difflib
first_file = 'E:\Elzero_learning\onefirst_file.txt'
second_file = 'E:\Elzero_learning\second_file.txt'
first_file_lines = open (first_file).readlines()
second_file_lines = open (second_file).readlines()
difference = difflib.HtmlDiff.make_file(first_file_lines ,second_file_lines ,first_file ,second_file )
difference_report = open("E:\Elzero_learning\output_file_1.html","w")
difference_report.write(difference)
difference_report.close()
However I receive this error traceback when executing the code:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS E:\Elzero_learning> & C:/python/Python39/python.exe "e:/Elzero_learning/compare files.py"
Traceback (most recent call last):
File "e:\Elzero_learning\compare files.py", line 7, in <module>
difference = difflib.HtmlDiff.make_file(first_file_lines ,second_file_lines ,first_file ,second_file )
File "C:\python\Python39\lib\difflib.py", line 1764, in make_file
return (self._file_template % dict(
AttributeError: 'list' object has no attribute '_file_template'
PS E:\Elzero_learning>

You need an instance of difflib.HtmlDiff on which to call make_file() so change:
difference = difflib.HtmlDiff.make_file(...)
to
difference = difflib.HtmlDiff().make_file(...)
which creates a difflib.HtmlDiff instance before calling its make_file() method.
You might like to review the documentation for class difflib.HtmlDiff to see if there are any default parameters that you would want to set.

Related

Constant variable names in all modules/functions

This is version 2 of my question, after the comment on v1 by Omer Dagry.
What's the best way to ensure that constants are available throughout my code?
I've created this constants.ini file that I want to be able to use in any module I create to ensure standard variables for certain functions.
; dd_config.ini
[DEBUG_TYPE]
DEBUG_SUBSTR = -1
DEBUG_START = 0
DEBUG_OS = 1
DEBUG_GENERAL = 2
DEBUG_END = 3
I have re-ordered program 1 so that it populates dd_con before importing dd_debug_exception:
from configparser import ConfigParser
# read the .ini file for some of the code
dd_con = ConfigParser()
dd_con.read(
"C:/Users/DD/dd_constants.ini"
)
# standard error reporting if debug needed
from test_debug_2 import dd_debug_exception
_SHORT = dd_con.get("DEBUG_STYLE", "DEBUG_SHORT")
print(_SHORT)
dd_debug_exception(0, "test", _SHORT)
Import dd_debug_exception does this:
def dd_debug_exception(debug_type,
debug_str,
debug_style: int = dd_con.get("DEBUG_TYPE",
"DEBUG_NORMAL")):
# Handle exceptions in a standard way
if debug_style == _SHORT:
print("hello")
When I try to run it I get the following error:
Traceback (most recent call last): File
"c:\Users\DD\test_config.py", line 9, in
from test_debug_2 import dd_debug_exception File "C:\Users\DD\test_debug_2.py", line 3, in
debug_style: int = dd_con.get("DEBUG_TYPE", NameError: name 'dd_con' is not defined
The import is still not recognising dd_con and therefore my standard variables.

macos python stat return unresolvable to group name value

So, as reported by a macos user, a python code that returns the group name breaks on his system (this is the only report from O(2) users in the code lifetime ~1y):
python3 -c "import grp; from pathlib import Path; fp = Path('example_file'); fp_gid = fp.stat().st_gid; print (fp_gid); print (grp.getgrgid(fp_gid).gr_name)"
In his case the stat looks like this:
os.stat_result(st_mode=33188, st_ino=118727615, st_dev=16777220, st_nlink=1, st_uid=142913934, st_gid=2048330233, st_size=3658004, st_atime=1647870524, st_mtime=1647374153, st_ctime=1647455470)
and trying to get gr_name breaks with:
2048330233
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'getgrgid(): gid not found: 2048330233'
So, in which situations macos can have such gids and how can i get the group names on such systems?

AttributeError: module 'yagmail' has no attribute 'SMTP'

Why do I get the below error?
I have imported yagmail. I have also tried with importing the smtplib module
Traceback (most recent call last):
File "C:/Users/Darsh/AppData/Local/Programs/Python/Python37-32/class programes/project1/my_yagmail.py", line 1, in <module>
from yagmail import *
File "C:/Users/Darsh/AppData/Local/Programs/Python/Python37-32/class programes/project1\yagmail.py", line 8, in <module>
yag = yagmail.SMTP(user="dar*******#gmail.com", password="*******", host='smtp.gmail.com')
AttributeError: module 'yagmail' has no attribute 'SMTP'
Code:
import yagmail
receiver = "pat*******#gmail.com"
body = "Hello there from Yagmail"
filename = "c.pdf"
yag = yagmail(user="dar**********#gmail.com", password="**********", host='smtp.gmail.com')
yag.send(
to=receiver,
subject="Yagmail test with attachment",
contents=body,
attachments=filename,
)
Looks like you have a script named "yagmail.py", I believe that the error is due to a namespace collision. My script was named the same thing, after renaming it the issue went away.
I saw a similar post on a different page in a different language that solved it (yay Google Translate!).

No attribute 'HookManager'

I am copying the key logger from this video: (https://www.youtube.com/watch?v=8BiOPBsXh0g) and running the code:
import pyHook, sys, logging, pythoncom
file_log = 'C:\Users\User\Google Drive\Python'
def OnKeyboardEvent(event):
logging.basicConfig(filename = file_log, level = logging.DEBUG, format = '%(message)s')
chr(event.Ascii)
logging.log(10, chr(event.Ascii))
return True
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.Pumpmessages()
This returns the error:
Traceback (most recent call last):
File "C:\Users\User\Google Drive\Python\pyHook.py", line 2, in <module>
import pyHook, sys, logging, pythoncom
File "C:\Users\User\Google Drive\Python\pyHook.py", line 12, in <module>
hooks_manager = pyHook.HookManager()
AttributeError: 'module' object has no attribute 'HookManager'
I am running Python 2.7.11 and a windows computer.
I don't know what the problem is; please help.
Thank you
I found the solution. If you open HookManager.py and change all 'key_hook' words to 'keyboard_hook' no more error occurs
I'm still unsure what the issue is but I found a solution.
If you move the program you are trying to run into the same folder as the HookManager.py file then it works.
For me this file was:
C:\Python27\Lib\site-packages\pyHook
Bro this line is wrong
file_log = 'C:\Users\User\Google Drive\Python'
As the system doesn't allow your program to write to the 'C' drive, you should use another path, like 'D' drive or 'E' drive or etc. as given below.
file_log = 'D:\keyloggerOutput.txt'
I had same message error after having installed pyWinhook-1.6.1 on Python 3.7 with the zip file pyWinhook-1.6.1.zip.
In application file, I replaced the import statement:" import pyWinhook as pyHook" with "from pywinhook import *". The problem was then solved.

Python 3 script using libnotify fails as cron job

I've got a Python 3 script that gets some JSON from a URL, processes it, and notifies me if there's any significant changes to the data I get. I've tried using notify2 and PyGObject's libnotify bindings (gi.repository.Notify) and get similar results with either method. This script works a-ok when I run it from a terminal, but chokes when cron tries to run it.
import notify2
from gi.repository import Notify
def notify_pygobject(new_stuff):
Notify.init('My App')
notify_str = '\n'.join(new_stuff)
print(notify_str)
popup = Notify.Notification.new('Hey! Listen!', notify_str,
'dialog-information')
popup.show()
def notify_notify2(new_stuff):
notify2.init('My App')
notify_str = '\n'.join(new_stuff)
print(notify_str)
popup = notify2.Notification('Hey! Listen!', notify_str,
'dialog-information')
popup.show()
Now, if I create a script that calls notify_pygobject with a list of strings, cron throws this error back at me via the mail spool:
Traceback (most recent call last):
File "/home/p0lar_bear/Documents/devel/notify-test/test1.py", line 3, in <module>
main()
File "/home/p0lar_bear/Documents/devel/notify-test/test1.py", line 4, in main
testlib.notify(notify_projects)
File "/home/p0lar_bear/Documents/devel/notify-test/testlib.py", line 8, in notify
popup.show()
File "/usr/lib/python3/dist-packages/gi/types.py", line 113, in function
return info.invoke(*args, **kwargs)
gi._glib.GError: Error spawning command line `dbus-launch --autolaunch=776643a88e264621544719c3519b8310 --binary-syntax --close-stderr': Child process exited with code 1
...and if I change it to call notify_notify2() instead:
Traceback (most recent call last):
File "/home/p0lar_bear/Documents/devel/notify-test/test2.py", line 3, in <module>
main()
File "/home/p0lar_bear/Documents/devel/notify-test/test2.py", line 4, in main
testlib.notify(notify_projects)
File "/home/p0lar_bear/Documents/devel/notify-test/testlib.py", line 13, in notify
notify2.init('My App')
File "/usr/lib/python3/dist-packages/notify2.py", line 93, in init
bus = dbus.SessionBus(mainloop=mainloop)
File "/usr/lib/python3/dist-packages/dbus/_dbus.py", line 211, in __new__
mainloop=mainloop)
File "/usr/lib/python3/dist-packages/dbus/_dbus.py", line 100, in __new__
bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 122, in __new__
bus = cls._new_for_bus(address_or_type, mainloop=mainloop)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NotSupported: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11
I did some research and saw suggestions to put a PATH= into my crontab, or to export $DISPLAY (I did this within the script by calling os.system('export DISPLAY=:0')) but neither resulted in any change...
You are in the right track. This behavior is because cron is run in a multiuser headless environment (think of it as running as root in a terminal without GUI, kinda), so he doesn't know to what display (X Window Server session) and user target to. If your application open, for example, windows or notification to some user desktop, then this problems is raised.
I suppose you edit your cron with crontab -e and the entry looks like this:
m h dom mon dow command
Something like:
0 5 * * 1 /usr/bin/python /home/foo/myscript.py
Note that I use full path to Python, is better if this kind of situation where PATH environment variable could be different.
Then just change to:
0 5 * * 1 export DISPLAY=:0 && /usr/bin/python /home/foo/myscript.py
If this still doesn't work you need to allow your user to control the X Windows server:
Add to your .bash_rc:
xhost +si:localuser:$(whoami)
If you want to set the DISPLAY from within python like you attempted with os.system('export DISPLAY=:0'), you can do something like this
import os
if not 'DISPLAY' in os.environ:
os.environ['DISPLAY'] = ':0'
This will respect any DISPLAY that users may have on a multi-seat box, and fall back to the main head :0.
If ur notify function, regardless of Python version or notify library, does not track the notify id [in a Python list] and deleting the oldest before the queue is completely full or on error, then depending on the dbus settings (in Ubuntu it's 21 notification max) dbus will throw an error, maximum notifications reached!
from gi.repository import Notify
from gi.repository.GLib import GError
# Normally implemented as class variables.
DBUS_NOTIFICATION_MAX = 21
lstNotify = []
def notify_show(strSummary, strBody, strIcon="dialog-information"):
try:
# full queue, delete oldest
if len(lstNotify)==DBUS_NOTIFICATION_MAX:
#Get oldest id
lngOldID = lstNotify.pop(0)
Notify.Notification.clear(lngOldID)
del lngOldID
if len(lstNotify)==0:
lngLastID = 0
else:
lngLastID = lstNotify[len(lstNotify) -1] + 1
lstNotify.append(lngLastID)
notify = Notify.Notification.new(strSummary, strBody, strIcon)
notify.set_property('id', lngLastID)
print("notify_show id %(id)d " % {'id': notify.props.id} )
#notify.set_urgency(Notify.URGENCY_LOW)
notify.show()
except GError as e:
# Most likely exceeded max notifications
print("notify_show error ", e )
finally:
if notify is not None:
del notify
Although it may somehow be possible to ask dbus what the notification queue max limit is. Maybe someone can help ... Improve this until perfection.
Plz
Cuz gi.repository complete answers are spare to come by.

Resources