I'm using a Raspberry Pi3 with python 3.5
For a project I need to autoprint every new JPEG image that will come into my folder on my Raspberry Pi3.
I did a lot of research, but did not come across the final answer yet.
What I do have is a printer connected to the Pi with USB and CUPS (that is working properly)
What I now need is a python script that will check if there is a new folder and then if so, autoprints it.
What I did find is a lot about FindFirstChangeAutofication
I tried this script:
(changed the path to watch into the folder that needs watching)
import os
import time
path_to_watch = ('/home/pi/jebenter/')
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
time.sleep (10)
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added: print "Added: ", ", ".join (added)
if removed: print "Removed: ", ", ".join (removed)
before = after`
It is not ready but not sure how to finish it..
And I need a way to send it to my printer.
Does somebody now how to help?
As I wrote in my comment above, you could print the files using lp or something similar.
I haven't tested this, but it should run:
import os
import time
import subprocess
path_to_watch = ('/home/pi/jebenter/')
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
time.sleep (10)
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added:
print "Added: ", ", ".join (added)
subprocess.Popen(["lp", "-d", printer_name, "--"] + added).communicate()
if removed: print "Removed: ", ", ".join (removed)
before = after
Related
I am working on a renaming function which is indexing the video files based on their Media creation date. As media creation date is not the file metadata, I am using the win32com.propsys module it works completely as expected till the last element of the FILES list but goes into loop for the remaining one file. I am unable to catch the issue. It would be really grateful to have positive suggestions.
import os
import pytz
import datetime
from win32com.propsys import propsys, pscon
os.chdir(r'H:\Study material\Python\practice')
current_path = r'H:\Study material\Python\practice'
files = os.listdir(current_path)
fi = []
li = []
for f in files:
properties = propsys.SHGetPropertyStoreFromParsingName(r'H:\Study material\Python\practice'+'\\'+f )
d = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
fi.append([str(d),f])
fi.sort()
l = [s[1] for s in fi]
for f in files:
i = l.index(f) + 1
new_name = str(i)+'-'+ f
li.append(new_name)
i = 0
for f in files:
os.rename(f,li[i])
i+=1
I guess the last item in sorted file list is a directory (maybe '__pycache__' ?). Try to check if it is really a file:
...
for f in files:
if not os.path.isfile(f):
print(f'not a file: {f}')
continue
properties = propsys.SHGetPropertyStoreFromParsingName(
os.path.join(r'H:\Study material\Python\practice', f) )
d = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
fi.append([str(d), f])
...
Or try to print every filename and new name and see if everything is correct:
...
for i, f in enumerate(files):
print(f, 'rename to', li[i])
os.rename(f, li[i])
Well i have 2 different scripts that i wrote
The first one is just getting an md5 hash from all files that are .exe
The other script is some agent who check's every 3 seconds if their is new files
in the directory .
now i need to make the agent check the files and also print every md5
this are my scripts :
import os, time
path_to_watch = "/root/PycharmProjects/untitled1"
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
time.sleep (3)
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added: print "Added: ", ", ".join (added)
if removed: print "Removed: ", ", ".join (removed)
before = after
And the second one who checks for md5
import glob
import os
import hashlib
work_path = '/root/PycharmProjects/untitled1/'
filenames = glob.glob("/root/PycharmProjects/untitled1/*.exe" )
if len(os.listdir(work_path)) > 0:
for filename in filenames:
with open(filename, 'rb') as inputfile:
data = inputfile.read()
print hashlib.md5(data).hexdigest()
else:
print '0'
Thanks for the help !
How about reducing the iteration from the hash generation, wrapping it into a function and call it when a new file is found:
import time
import glob
import os
import hashlib
def md5(filename):
with open(filename, 'rb') as inputfile:
data = inputfile.read()
print filename, hashlib.md5(data).hexdigest()
path_to_watch = "."
before = os.listdir(path_to_watch)
while 1:
time.sleep(3)
after = os.listdir(path_to_watch)
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added:
print "Added: ", ", ".join(added)
for filename in added:
md5(filename)
if removed:
print "Removed: ", ", ".join(removed)
before = after
Also stripped some unnecessary dict stuff from the code.
I suggest you take it as a challenge to reduce the number of statements and the number of data transformations to a minimum while keeping the function of the script. At the same time it might be worth a look to the Python Style Guide ;)
So, i wrote this to monitor a folder for new pictures and print any that are found. It works, but I am assuming there is a more robust/efficient way to tackle this problem as I want it to run for 5-6 hours at a time.
My main problem is that I don't like using "open" while loops like this....
Would anyone tackle this differently? If so, would anyone be willing to explain?
import os
import glob
import win32com.client
import time
from pywinauto.findwindows import find_window
from pywinauto.win32functions import SetForegroundWindow
printed = []
i = 10
while i < 1000000000000000:
files = glob.glob("C://Users//pictures/*.jpg")
for filename in files:
print filename
try:
if printed.index(str(filename)) >= 0:
print printed.index(filename)
print "Image found"
except ValueError:
printed.append(filename)
os.startfile(filename, "print")
shell = win32com.client.Dispatch("WScript.Shell")
time.sleep(2)
SetForegroundWindow(find_window(title='Print Pictures'))
shell.AppActivate("Print Pictures")
shell.SendKeys("{ENTER}")
i = i + 1
time.sleep(5)
link below is related post. instead of using a long while loop you can use a watcher to trigger your operation.
How to detect new or modified files
Big thanks to scope for his comment, i have added my printing lines to the example and it works well. Code posted below for anyone who wants it, commented code is in the link code posted. Now to tidy up a few other things....
import os
import win32file
import win32event
import win
import glob
import win32com.client
import time
from pywinauto.findwindows import find_window
from pywinauto.win32functions import SetForegroundWindow
def print_photo(filename):
print filename
filename = path_to_watch +"\\" + filename[0]
os.startfile(filename, "print")
shell = win32com.client.Dispatch("WScript.Shell")
time.sleep(2)
SetForegroundWindow(find_window(title='Print Pictures'))
shell.AppActivate("Print Pictures")
shell.SendKeys("{ENTER}")
path_to_watch = os.path.abspath ("C:\\Users\\Ciaran\\Desktop\\")
change_handle = win32file.FindFirstChangeNotification (
path_to_watch,
0,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)
try:
old_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
result = win32event.WaitForSingleObject (change_handle, 500)
if result == win32con.WAIT_OBJECT_0:
new_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in new_path_contents if not f in old_path_contents]
print_photo(added)
deleted = [f for f in old_path_contents if not f in new_path_contents]
if added: print "Added: ", ", ".join (added)
if deleted: print "Deleted: ", ", ".join (deleted)
old_path_contents = new_path_contents
win32file.FindNextChangeNotification (change_handle)
finally:
win32file.FindCloseChangeNotification (change_handle)
I have a little code that allows me to print images arriving in a folder.
But I'd like them to be deleted just after having been printed - I want to try this on a RaspberryPI and I will not have enough space to store all images.
If someone can help me it would be very much appreciated.
Here is my code:
monRep = "/Users/XX/Desktop/XXX/"
import os, mimetypes, random
while True:
fpaths = []
for fname in os.listdir(monRep):
fpath = os.path.join(monRep, fname)
if os.path.isfile(fpath):
mt = mimetypes.guess_type(fpath)[0]
ext = os.path.splitext(fpath)[1]
if mt: mt = mt.split('/')[0].lower()
else: mt = False
#if ext.lower() in ('.bmp','.pict', '.JPG', '.jpg', '.pdf'): mt = 'image'
if mt in ('image',): fpaths.append(fpath)
for fpath in fpaths:
newpath = fpath.replace('/Users/XX/Desktop/XXX/','/Users/XX/Desktop/XXX2/')
os.rename(fpath,newpath)
command = "lpr "+newpath
print (command)
os.system(command)
I tried to write at the end
os.remove ('/Users/Aym/Desktop/eden2/')
But then I had this :
SError: [Errno 1] Operation not permitted: '/Users/XX/Desktop/XXX2/'
I tried the shutil method recommanded on this forum
import os
import shutil
for root, dirs, files in os.walk('/Users/XX/Desktop/XXX2/'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
but nothing happened
I have also less space on a Raspberry. What you can exchange first of all is:
LIST_NAME = ['.jpg', '.bmp', '.mickey_mouse']
file = [file for file in os.listdir(CAMERA_DIR) for type_name in LIST_NAME if file.endswith(type_name)]
That is somehow equivalent to your whole search engine above.
where LIST_NAME is whatever you look for and CAMERA_DIR == "/Users/XX/Desktop/XXX/"
The lines above will make your code easier and compact without usage of extra modules.
You can use a simple move action from XX to XX2 (shutil module) for each found file under os.path.join(CAMERA_DIR, file_name).
Last step after you print or do whatever, remove completely the XX2 folder with simple command:
shutil.rmtree(XX2)
This is definitely work and clean up your code in Python3. Have fun!
What I can even recommend is: usage of /tmp/NAMEXX folder. In worst case it is only on the temporary folder of your raspberry!
I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyperlinks only to the local files on the USB drive.
#!/usr/bin/python
import os.path
import os
import shutil
import re
# Create the videos directory in the current location
# If the directory exists ignore it
def createDirectory():
directory = "videos"
if not os.path.isdir("./" + directory + "/"):
os.mkdir("./" + directory + "/")
print "Videos Folder Created."
else:
print "Video Folder Exists."
print "---------------------"
# Move all the files in the root directory with the .wmv extension
# to the videos folder
def moveVideos():
for file in os.listdir("."):
if os.path.splitext(file)[1] == ".wmv":
print "Moving:", file
shutil.move(file, os.path.join("videos", file))
def createHTML():
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.writelines(videoDirectory)
r = re.compile(r"(\\[^ ]+)")
print r.sub(r'\1', videoDirectory)
createDirectory()
moveVideos()
createHTML()
import cgi
def is_video_file(filename):
return filename.endswith(".wmv") # customize however you like
def createHTML():
videoDirectory = os.listdir("videos")
with open("videos.html", "w") as f:
f.write("<html><body><ul>\n")
for filename in videoDirectory:
if is_video_file(filename):
f.write('<li>%s</li>\n' %
(cgi.escape(filename, True), cgi.escape(filename)))
f.write("</ul></body></html>\n")
Don't do f.writelines(videoDirectory) and then regex. Besides you're only printing to the console with that regex subsitution.
Do
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.write('<html><head></head><body><ul>'
f.writelines(['<li>%s</li>' % (f, f) for f in videoDirectory])
f.write('</ul></body></html>')
def createHTML():
h = open("videos.html", 'w')
for vid in os.listdir:
path = "./videos" + vid
f = open(path, r)
h.write("<a href='"+f.name+"'>"+f.name[f.name.rfind('\\') +1 :]+"</a>")
f.close()
h.close()
print "done writing HTML file"