Python subprocess.Popen not stop when using kill() - python

I am trying to restart a python process, when file changes are made.
Dir Structure
/root
|_ test.py
|_ main.py
main.py
import os
import sys
import shutil
import _thread
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent
cwd = os.getcwd()
pj = os.path.join
exists = os.path.exists
class Reloader(FileSystemEventHandler):
def __init__(self, openProc: subprocess.Popen = None, cmd=""):
super().__init__()
self.__cmd = cmd
self.openProc = openProc if openProc else subprocess.Popen(self.__cmd, cwd=cwd, shell=True)
def on_any_event(self, event):
if event.is_directory:
return
_, ext = os.path.splitext(event.src_path)
if ext[1:] in ["py", "cpp", "c", "h", "hpp"]:
print(":: CHANGES DETECTED, RELOADING ::")
print("--changed file '{}'--".format(event.src_path))
self.killProc()
def killProc(self):
self.openProc.kill()
def getInput():
global cwd
cwd = os.getcwd()
return input("⚡>" + cwd + ">")
if __name__ == "__main__":
while True:
userInput = getInput()
split = userInput.split(" ")
print("Starting CMD Command With Reloader...")
while True:
try:
event_handler = Reloader(cmd=split)
observer = Observer()
observer.schedule(event_handler, cwd, recursive=True)
observer.start()
while event_handler.openProc.poll() is None:
pass
observer.stop()
except KeyboardInterrupt:
break
test.py
import time
c = 0
while True:
c+=1
print(c)
time.sleep(1)
When I run that:
E:\electrocli>py main.py
⚡>E:\electrocli>py test.py
Starting CMD Command With Reloader...
1
2
3
4
:: CHANGES DETECTED, RELOADING ::
--changed file 'E:\electrocli\test.py'--
:: CHANGES DETECTED, RELOADING ::
--changed file 'E:\electrocli\test.py'--
5
1
6
2
7
3
This shows that, the older process, whis should be revoked by subprocess.Popen.kill has not ended. I want to kill the old process, and start the new one. Is there any way to do that? Or, is there any mistake in my code?

Related

Python parallel thread that consume Watchdog queue events

I have this code that should put an event in a queue each time an external program (TCPdump) creates a *.pcap file in my directory.
My problem is that I always get an empty queue, although I got the print from process() function.
What am I doing wrong? Is the queue correctly defined and shared between the two classes?
EDIT-----------------
I maybe understood why I got an empty queue, I think it is because I'm printing the queue that I initialized before it gets filled by Handler class.
I modified my code and created two processes that should consume the same queue, but now the execution stuck on queue.put() and the thread ReadPcapFiles() stop running.
Here the updated code:
import time
import pyshark
import concurrent.futures
import threading
import logging
from queue import Queue
from multiprocessing import Process
from watchdog.observers import Observer, api
from watchdog.events import PatternMatchingEventHandler
class Handler(PatternMatchingEventHandler):
patterns = ["*.pcap", "*.pcapng"]
def __init__(self, queue):
PatternMatchingEventHandler.__init__(self)
self.queue = queue
def process(self, event):
#print(f'event type: {event.event_type} path : {event.src_path}')
self.queue.put(event.src_path)
logging.info(f"Storing message: {self.queue.qsize()}")
print("Producer queue: ", list(self.queue.queue))
#self.queue.get()
def on_created(self, event):
self.process(event)
def StartWatcher(watchdogq, event):
path = 'C:\\...'
handler = Handler(watchdogq)
observer = Observer()
while not event.is_set():
observer.schedule(handler, path, recursive=False)
print("About to start observer")
observer.start()
try:
while True:
time.sleep(1)
except Exception as error:
observer.stop()
print("Error: " + str(error))
observer.join()
def ReadPcapFiles(consumerq, event):
while not event.is_set() or not consumerq.empty():
print("Consumer queue: ", consumerq.get())
#print("Consumer queue: ", list(consumerq.queue))
# pcapfile = pyshark.FileCapture(self.queue.get())
# for packet in pcapfile:
# countPacket +=1
if __name__ == '__main__':
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S")
logging.getLogger().setLevel(logging.DEBUG)
queue = Queue()
event = threading.Event()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(StartWatcher,queue, event)
executor.submit(ReadPcapFiles,queue, event)
time.sleep(0.1)
logging.info("Main: about to set event")
event.set()
OLD CODE:
import time
from queue import Queue
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class Handler(PatternMatchingEventHandler):
patterns = ["*.pcap", "*.pcapng"]
def __init__(self, queue):
PatternMatchingEventHandler.__init__(self)
self.queue = queue
def process(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
self.queue.put(event.src_path)
def on_created(self, event):
self.process(event)
class Watcher():
def __init__(self, path):
self.queue = Queue()
self.observer = Observer()
self.handler = Handler(self.queue)
self.path = path
def start(self):
self.observer.schedule(self.handler, self.path, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
self.queue.get()
print(list(self.queue.queue))
except Exception as error:
self.observer.stop()
print("Error: " + str(error))
self.observer.join()
if __name__ == '__main__':
watcher = Watcher('C:\\...')
watcher.start()
This is working for me (I got the main idea from this answer, thanks!) but notice that I consider this a workaround, so if someone has a better solution to this or can better explain the reason of such behavior in Python, please do not hesitate to answer!
My guess is that I had two main problems:
- I was starting Watchdog process inside another thread (and that was blocking somehow my queue consuming thread).
- Python threading does not work really in parallel and therefore starting an independent process was necessary.
Here my code:
import time
import pyshark
import threading
import logging
import os
from queue import Queue
from multiprocessing import Process, Pool
from watchdog.observers import Observer, api
from watchdog.events import PatternMatchingEventHandler
from concurrent.futures import ThreadPoolExecutor
class Handler(PatternMatchingEventHandler):
patterns = ["*.pcap", "*.pcapng"]
def __init__(self, queue):
PatternMatchingEventHandler.__init__(self)
self.queue = queue
def process(self, event):
self.queue.put(event.src_path)
logging.info(f"Storing message: {self.queue.qsize()}")
print("Producer queue: ", list(self.queue.queue))
def on_created(self, event):
#wait that the transfer of the file is finished before processing it
file_size = -1
while file_size != os.path.getsize(event.src_path):
file_size = os.path.getsize(event.src_path)
time.sleep(1)
self.process(event)
def ConsumeQueue(consumerq):
while True:
if not consumerq.empty():
pool = Pool()
pool.apply_async(ReadPcapFiles, (consumerq.get(), ))
else:
time.sleep(1)
def ReadPcapFiles(get_event):
createdFile = get_event
print(f"This is my event in ReadPacapFile {createdFile}")
countPacket = 0
bandwidth = 0
pcapfile = pyshark.FileCapture(createdFile)
for packet in pcapfile:
countPacket +=1
bandwidth = bandwidth + int(packet.length)
print(f"Packet nr {countPacket}")
print(f"Byte per second {bandwidth}")
if __name__ == '__main__':
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S")
logging.getLogger().setLevel(logging.DEBUG)
queue = Queue()
path = 'C:\\...'
worker = threading.Thread(target=ConsumeQueue, args=(queue, ), daemon=True)
print("About to start worker")
worker.start()
event_handler = Handler(queue)
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
print("About to start observer")
observer.start()
try:
while True:
time.sleep(1)
except Exception as error:
observer.stop()
print("Error: " + str(error))
observer.join()
There is an excellent library which provides concurrent access to the items within that queue. The queue is also persistent[file based as well as database based], so if the program crashes, you can still consume events from the point where the program crashed.
persist-queue

File Monitoring using watchdog library

I have written one python script to monitor one local folder which is having only .txt files and i want to start this script automatically if some changes happened to the folder(created,deleted or updated)
I tried to run this script and also tried to make changes in the directory, but i couldn't see any output and no error messages. It always says "Process finished with exit code 0" can any one review my code and give me some tips where to correct to get the expected out put.
import os
import sys
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
#Step 1 Create the event handler
if __name__ == "__main__":
patterns = ".txt"
ignore_patterns = None
ignore_directories = False
case_sensitive = True
event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)
#step 2 Handle all the events
def on_created(event):
print("new files has been created!")
def on_deleted(event):
print("Some files has been Deleted")
def on_modified(event):
print("Some files has been modified")
def on_moved(event):
print("Some files has been moved")
#step 3 specify to the handler that we want these functions to be called
event_handler.on_created = on_created
event_handler.on_deleted = on_deleted
event_handler.on_modified = on_modified
event_handler.on_moved = on_moved
#step 4 create an observer
path = "T:\Laboratory\Instruments\Worklists\TrackMateRacks\old"
go_recursively = True
my_observer = Observer()
my_observer.path(event_handler, path, recursive=go_recursively)
# start the observer
my_observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
my_observer.stop()
my_observer.join()
you have to move the lines after " # start the observer" to the very left.
otherwise there will be executed nothing. that lines are part of on_moved(). but you want them to be executed if you start the script.
or
for most programs it's useful to add this line:
if __name__ == '__main__':
bevore line "# start the observer"
than your my_observer.start() will be executed, if you call your script. but if you import your script in another script, this will not be executed, but the other script can use all the functions, you created.
It seems, that you're really new to Python. You've to watch the indents, they're part of the syntax.
Exceptionally I reformat the complete code for you:
import os
import sys
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
#Step 1 Create the event handler
patterns = ".txt"
ignore_patterns = None
ignore_directories = False
case_sensitive = True
event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)
#step 2 Handle all the events
def on_created(event):
print("new files has been created!")
def on_deleted(event):
print("Some files has been Deleted")
def on_modified(event):
print("Some files has been modified")
def on_moved(event):
print("Some files has been moved")
#step 3 specify to the handler that we want these functions to be called
event_handler.on_created = on_created
event_handler.on_deleted = on_deleted
event_handler.on_modified = on_modified
event_handler.on_moved = on_moved
#step 4 create an observer
def main():
path = "T:\Laboratory\Instruments\Worklists\TrackMateRacks\old"
go_recursively = True
my_observer = Observer()
my_observer.path(event_handler, path, recursive=go_recursively)
# start the observer
my_observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
my_observer.stop()
my_observer.join()
if __name__ == "__main__":
main()
#end of file
Good luck!

from cmd import Cmd, (not working with class MyPrompt)

This is a helper command line in python, I was looking to add custom stuff for myself of course and was adding in a IP searcher. Have been getting this error for a while now, cant seem to figure it out and its critical to start my prompt. Any Tips appreciated, Good day.
from cmd import Cmd
import pyautogui as pag #Future#
import time #Debugging/Future#
import sys,os
clear = lambda : os.system('cls')
#############################################
from colorama import init
from ctypes.test.test_pickling import name
init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected
from termcolor import cprint
from pyfiglet import figlet_format
##############################################
class MyPrompt(Cmd):
#staticmethod
def do_lineage(self):
"""Switch to Lineage 2 Helper"""
print("Switching to Lineage 2 Helper....")
os.system(r"python C:\Users\David\eclipse-workspace\CMD\src\L2.py")
#staticmethod
def do_ip(self):
"""IP"""
print("Switching to IP stuff.... ")
os.system(r"python C:\Users\David\eclipse-workspace\CMD\src\Play.py")
#staticmethod
def do_quit(self):
"""Quits the program."""
print("Quitting...")
raise SystemExit
#staticmethod
def do_Movies(self,num):
"""1-3 different sites, or all for """
if num == 1:
print("https://genvideos.org")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=https://genvideos.org")
if num == 2:
print("https://www3.gomovies.sc")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=https://www3.gomovies.sc")
if num == 3:
print("https://vioozgo.org/")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=google.com")
if num == "all":
print("https://genvideos.org")
print("https://www3.gomovies.sc")
print("https://vioozgo.org/")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=google.com")
if __name__ == '__main__':
clear()
prompt = MyPrompt()
prompt.prompt = '> '
prompt.cmdloop(cprint(figlet_format('--------\nHelper\n--------', font='smslant'), "yellow"))
My error:
Traceback (most recent call last):
File "C:\Users\David\eclipse-workspace\CMD\src\Cmdd.py", line 1, in <module>
from cmd import Cmd
ImportError: cannot import name 'Cmd'
This was previously working, must of changed something. Where am I going wrong?
When I encounter an issue like this, I like drop myself into a debugger in the command line and start poking around.
To do this, I add import pdb; pdb.set_trace() near where the issue is happening, in this case at the top of the file. Once in debug mode, I starting looking at the object that is causing the issue. I'd probably start with changing the import statement to import the full cmd module, and then I would dir said module. You can print cmd.__file__ to see where it is coming from
import cmd
import pdb; pdb.set_trace()
# code stops here so you can start digging
# dir(cmd) will tell you what properties the module has
# cmd.__file__ will tell you the file path
from cmd import Cmd
import pyautogui as pag #Future#
import time #Debugging/Future#
import sys,os
clear = lambda : os.system('cls')
#############################################
from colorama import init
from ctypes.test.test_pickling import name
init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected
from termcolor import cprint
from pyfiglet import figlet_format
##############################################
class MyPrompt(Cmd):
#staticmethod
def do_lineage(self):
"""Switch to Lineage 2 Helper"""
print("Switching to Lineage 2 Helper....")
os.system(r"python C:\Users\David\eclipse-workspace\CMD\src\L2.py")
#staticmethod
def do_ip(self):
"""IP"""
print("Switching to IP stuff.... ")
os.system(r"python C:\Users\David\eclipse-workspace\CMD\src\Play.py")
#staticmethod
def do_quit(self):
"""Quits the program."""
print("Quitting...")
raise SystemExit
#staticmethod
def do_Movies(self,num):
"""1-3 different sites, or all for """
if num == 1:
print("https://genvideos.org")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=https://genvideos.org")
if num == 2:
print("https://www3.gomovies.sc")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=https://www3.gomovies.sc")
if num == 3:
print("https://vioozgo.org/")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=google.com")
if num == "all":
print("https://genvideos.org")
print("https://www3.gomovies.sc")
print("https://vioozgo.org/")
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome --app=google.com")
if __name__ == '__main__':
clear()
prompt = MyPrompt()
prompt.prompt = '> '
prompt.cmdloop(cprint(figlet_format('--------\nHelper\n--------', font='smslant'), "yellow"))

Python watchdog for files from two different directories

I am trying to listen to filesystem changes using the watchdog module of Python. I want to monitor the files from two different directories. For a single file watch, I used PatternMatchingEventHandler from watchdog.events. I want to use the same for multiple directories.
code:
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class EventHandler(PatternMatchingEventHandler):
def on_modified(self, event):
super(EventHandler, self).on_modified(event)
print event
if __name__ == "__main__":
dir_name = ["/home/user1/first", "/home/user1/second"]
observer = Observer()
patterns = ["/home/user1/first/first.log","/home/user1/second/second.log")]
for i in xrange(len(dir_name)):
event_handler = EventHandler(patterns = patterns[i])
observer.schedule(event_handler, dir_name[i], recursive=True)
observer.start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
observer.stop()
In the above code, I tried to do multiple directory observing format and create an event handler for each of the files. It's not working for me. Is there anything that I am missing here?? What is the way to do this??
Thanks.
some wrong in here
EventHandler(patterns = patterns[i])
arg patterns is a type of list, so you can use like this
patterns = [["/home/user1/first/first.log"], ["/home/user1/second/second.log"]]
EventHandler(patterns = patterns[i])
Though it does not use the watchdog library , this will the easy way just to check if the specific type of files are added or removed
if u want to check which files u can append them using any variable and store them in array
import os
import fnmatch
import threading
import time
initial_count = 0
flag = 0
files = []
path = ["/home/kirti/workspace/pythonproject6/img", "/home/kirti/workspace/pythonproject6/copy"]
def taskcount(path, flag, initial_count):
while 1:
time.sleep(3)
new_count = len(fnmatch.filter(os.listdir(path), "*.jpg"))
if new_count > initial_count:
if flag != 0:
print("Added \nCount :", new_count, "=", path)
else:
print(new_count)
if new_count < initial_count:
print("Removed \nCount :", new_count, "=", path)
initial_count = new_count
flag = 1
for j in range(len(path)):
t = threading.Thread(target=taskcount, args=(path[j], flag, initial_count))
t.start()
I am using python3, LINUX OS
With a minor modification as suggested above and some additions from myside too this is working now
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class EventHandler(PatternMatchingEventHandler):
def on_modified(self, event):
super(EventHandler, self).on_modified(event)
print(event)
if __name__ == "__main__":
dir_name = ["/home/don/test1", "/home/don/test2"]
observer = Observer()
threads=[]
patterns = [['*.log'],['*.ok']]
for i in range(len(dir_name)):
event_handler = EventHandler(patterns = patterns[i],ignore_directories=True,case_sensitive=False)
observer.schedule(event_handler, dir_name[i], recursive=True)
threads.append(observer)
observer.start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Comparing with mine, you are lacking of observer.join() at the EOF. Try with that.
EDIT
Try this code below:
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class EventHandler(PatternMatchingEventHandler):
def on_modified(self, event):
super(EventHandler, self).on_modified(event)
print event
if __name__ == "__main__":
observer = Observer()
patterns = ["/home/user1/first/first.log","/home/user1/second/second.log"]
for pattern in patterns:
event_handler = EventHandler(patterns=pattern)
observer.schedule(event_handler, dir_name[i], recursive=True)
observer.start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
observer.stop()
observer.join()

peculiar error on ntpath.py

I am trying to write a wrapper like thing on vlc player on windows 7 so that it can load next and previous files in folder with a keystroke. What I do in it is, I take a filepath as argument make an instance of the vlc class and using pyHook, scan for keys and when specific keystrokes are detected call the play_next and play_prev methods on the instance. The methods work by killing the last process and spawning new vlc with next file found by get_new_file method. It works the first couple of times and then gives the peculiar error.
None
None
Traceback (most recent call last):
File "C:\Python27\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "filestuff.py", line 64, in kbwrap
kbeventhandler(event,instance)
File "filestuff.py", line 11, in kbeventhandler
instance.play_prev()
File "filestuff.py", line 34, in play_prev
f=self.get_new_file(-1)
File "filestuff.py", line 40, in get_new_file
dirname= os.path.dirname(self.fn)
File "C:\Python27\lib\ntpath.py", line 205, in dirname
return split(p)[0]
File "C:\Python27\lib\ntpath.py", line 178, in split
while head2 and head2[-1] in '/\\':
TypeError: an integer is required
here is the code:
import os
import sys
import pythoncom, pyHook
import win32api
import subprocess
import ctypes
def kbeventhandler(event,instance):
if event.Key=='Home':
instance.play_prev()
if event.Key=='End':
instance.play_next()
return True
class vlc(object):
def __init__(self,filepath,vlcp):
self.fn=filepath
self.vlcpath=vlcp
self.process = subprocess.Popen([self.vlcpath, self.fn])
def kill(self):
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, self.process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
print self.process.poll()
def play_next(self):
self.kill()
f=self.get_new_file(1)
self.process = subprocess.Popen([self.vlcpath, f])
self.fn=f
def play_prev(self):
self.kill()
f=self.get_new_file(-1)
self.process = subprocess.Popen([self.vlcpath, f])
self.fn=f
def get_new_file(self,switch):
dirname= os.path.dirname(self.fn)
supplist=['.mkv','.flv','.avi','.mpg','.wmv']
files = [os.path.join(dirname,f) for f in os.listdir(dirname) if (os.path.isfile(os.path.join(dirname,f)) and os.path.splitext(f)[-1]in supplist)]
files.sort()
try: currentindex=files.index(self.fn)
except: currentindex=0
i=0
if switch==1:
if currentindex<(len(files)-1):i=currentindex+1
else:
if currentindex>0:i=currentindex-1
return files[i]
def main():
vlcpath='vlc'
if os.name=='nt': vlcpath='C:/Program Files (x86)/VideoLAN/VLC/vlc.exe'
fn='H:\\Anime\\needless\\Needless_[E-D]\\[Exiled-Destiny]_Needless_Ep11v2_(04B16479).mkv'
if len(sys.argv)>1:
fn=sys.argv[1] #use argument if available or else use default file
instance=vlc(fn,vlcpath)
hm = pyHook.HookManager()
def kbwrap(event):
kbeventhandler(event,instance)
hm.KeyDown = kbwrap
hm.HookKeyboard()
pythoncom.PumpMessages()
if __name__ == '__main__':
main()
here too: http://pastebin.com/rh82XGzd
The problem was that
in main I set hm.KeyDown = kbwrap and then from function kbwrap called the actual event handler kbeventhandler but didn't return any value from kbwrap
def kbwrap(event):
return kbeventhandler(event,flag)
hm.KeyDown = kbwrap
and I also offloaded the vlc work to a different thread as pyHook wasn't playing nice with subprocess.
final working code:
import os
import sys
import pythoncom, pyHook
import win32api
import subprocess
import ctypes
import threading
from multiprocessing import *
class vlcThread(threading.Thread):
def __init__(self,filepath,vlcp,fl):
threading.Thread.__init__(self)
self.fn,self.vlcpath,self.flag=filepath,vlcp,fl
self.daemon=True
self.start() # invoke the run method
def run(self):
vlcinstance=vlc(self.fn,self.vlcpath)
while True:
if(self.flag.value==1):
vlcinstance.play_next()
self.flag.value=0
if(self.flag.value==-1):
vlcinstance.play_prev()
self.flag.value=0
def kbeventhandler(event,flag):
if event.Key=='Home':
flag.value =-1
return False
if event.Key=='End':
flag.value =1
return False
return True
class vlc(object):
def __init__(self,filepath,vlcp):
self.fn=filepath
self.vlcpath=vlcp
self.process = subprocess.Popen([self.vlcpath,self.fn],close_fds=True)
def kill(self):
p, self.process = self.process, None
if p is not None and p.poll() is None:
p.kill()
p.wait()
def play_next(self):
self.kill()
f=self.get_new_file(1)
self.process = subprocess.Popen([self.vlcpath,f],close_fds=True)
self.fn=f
def play_prev(self):
self.kill()
f=self.get_new_file(-1)
self.process = subprocess.Popen([self.vlcpath, f],close_fds=True)
self.fn=f
def get_new_file(self,switch):
dirname= os.path.dirname(self.fn)
supplist=['.mkv','.flv','.avi','.mpg','.wmv','ogm','mp4']
files = [os.path.join(dirname,f) for f in os.listdir(dirname) if (os.path.isfile(os.path.join(dirname,f)) and os.path.splitext(f)[-1]in supplist)]
files.sort()
try: currentindex=files.index(self.fn)
except: currentindex=0
i=0
if switch==1:
if currentindex<(len(files)-1):i=currentindex+1
else:
if currentindex>0:i=currentindex-1
return files[i]
def main():
vlcpath='vlc'
flag=Value('i')
flag.value=0
if os.name=='nt': vlcpath='C:/Program Files (x86)/VideoLAN/VLC/vlc.exe'
fn='H:\\Anime\\needless\\Needless_[E-D]\\[Exiled-Destiny]_Needless_Ep11v2_(04B16479).mkv'
if len(sys.argv)>1:
fn=sys.argv[1] #use argument if available or else use default file
t=vlcThread(fn,vlcpath,flag)
hm = pyHook.HookManager()
def kbwrap(event):
return kbeventhandler(event,flag)
hm.KeyDown = kbwrap
hm.HookKeyboard()
pythoncom.PumpMessages()
if __name__ == '__main__':
main()

Categories