Python, selecting a specific file - python-3.x

I need to select a specific file, after specifying the number of this file in "if"...
Instead of "MTS.txt " we need the full path to the selected file using a digit!
I have not found any information about this on the Internet. Perhaps he made up his request badly!
from email import message
from click import clear
import pywhatkit
import pyfiglet
import os
import time
directory = 'MTS/'
# files = os.listdir(directory)
f = True
while (f==True):
def main():
os.system('CLS')
# print(files)
mtstxt = pyfiglet.figlet_format("Wa Helper", font = "smslant")
print(mtstxt)
def send_message_inst():
mobile = '+7' + input(' Номер: +7')
with os.scandir(directory) as files:
for i, file in enumerate(files):
print(' ', i + 1, file.name)
nof = os.listdir(path="MTS/")
# print(len(nof))
while True:
tarif = int(input(' Вариант: '))
if tarif >= 1 and tarif <= int(len(nof)):
msg = open("MTS.txt", encoding='UTF-8')
message = msg.read()
msg.close()
break
else:
os.system('CLS')
print(mtstxt)
print(' Номер:', mobile)
with os.scandir(directory) as files:
for i, file in enumerate(files):
print(' ', i + 1, file.name)
print("\033[31m{}\033[0m".format(" Ошибка - неверный вариант!"))
pywhatkit.sendwhatmsg_instantly(phone_no=mobile, message=message)
send_message_inst()
os.system('CLS')
sndtxt = pyfiglet.figlet_format("Sent!", font = "smslant")
print(sndtxt)
time.sleep(5)
if __name__ == '__main__':
main()
else:
break

Related

Python - filesystem link and/or selectable text

How do I put a filesystem link and/or selectable text in the output Tkinter label?
Basically, I would like the user to be able to click on the folder that comes with the message "NO TRANSMITTAL", or at least copy and paste from the Tkinter window.
Also, I know this code can be much better looking, so please do not save any advices :):)
Thanks in advance.
Code below.
import os
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
gui = Tk()
gui.title("MY SCRIPT")
list_of_folders=[]
out_folders=[]
substring_transmittal="Transmittal"
current_folder=('')
substring_drawings_0='.pdf'
def getFolderPath():
folder_selected = filedialog.askdirectory()
folderPath.set(folder_selected)
def doStuff():
folder = folderPath.get()
final_print=("Checking for Transmittal in %s" %(folder))
for path, dirs, files in os.walk(folder):
list_of_folders.append(path)
for i in list_of_folders:
if '6_Out' in i:
out_folders.append(i)
else:
pass
for o in out_folders:
os.chdir(o)
current_folder=os.getcwd()
a=os.listdir(current_folder)
string_check_transmittal = list(filter(lambda x: substring_transmittal in x, a))
string_check_drawings_0 = list(filter(lambda x: substring_drawings_0 in x, a))
string_check_drawings_1 = list(filter(lambda x: substring_drawings_1 in x, a))
if string_check_transmittal:
out=str(current_folder[len(folder):])
final_print += "\n%s ---> Transmittal OK" %(out)
else:
if string_check_drawings_0:
if string_check_drawings_1:
out=str(current_folder[len(folder):])
final_print += "\n%s ------ NO TRANSMITTAL ------" %(out)
for i in a:
print(' ',i)
out=i
final_print += "\n %s" %(out)
else:
pass
else:
pass
string_check_drawings_0 = ''
string_check_drawings_1 = ''
display_text.config(text=(final_print))
folderPath = StringVar()
a = Label(gui ,text="Enter name")
a.grid(row=0,column = 0)
E = Entry(gui,textvariable=folderPath)
E.grid(row=0,column=1)
btnFind = ttk.Button(gui, text="Browse Folder",command=getFolderPath)
btnFind.grid(row=0,column=4)
c = ttk.Button(gui ,text="Check", command=doStuff)
c.grid(row=4,column=0)
d = ttk.Button(gui ,text="Exit", command=gui.destroy)
d.grid(row=4,column=4)
display_text=Label(gui, borderwidth=3, justify=LEFT)
display_text.grid(row=5,column=0,padx=5)
gui.mainloop()

How to remake this python3 dircache/cmd python3

i am wondering how to go about making this short test in python3, cmd is supported in python3 but dircache is not... currently only works on python2 but looking to change it to work in python3, thanks!
#!/usr/bin/env python
import cmd
import dircache
class MyCmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = '(MyCmd)'
def do_test(self, line):
print('cmd test ' + line)
def complete_test(self, text, line, begidx, endidx):
""" auto complete of file name.
"""
line = line.split()
if len(line) < 2:
filename = ''
path = './'
else:
path = line[1]
if '/' in path:
i = path.rfind('/')
filename = path[i+1:]
path = path[:i]
else:
filename = path
path = './'
ls = dircache.listdir(path)
ls = ls[:] # for overwrite in annotate.
dircache.annotate(path, ls)
if filename == '':
return ls
else:
return [f for f in ls if f.startswith(filename)]
if __name__ == '__main__':
mycmd = MyCmd()
mycmd.cmdloop()
Ive tried using this instead of dircache but had no luck
#lru_cache(32)
def cached_listdir(d):
return os.listdir(d)
Here you go check out the load function
import os
import glob
import cmd
def _append_slash_if_dir(p):
if p and os.path.isdir(p) and p[-1] != os.sep:
return p + os.sep
else:
return p
class MyShell(cmd.Cmd):
prompt = "> "
def do_quit(self, line):
return True
def do_load(self, line):
print("load " + line)
def complete_load(self, text, line, begidx, endidx):
before_arg = line.rfind(" ", 0, begidx)
if before_arg == -1:
return # arg not found
fixed = line[before_arg+1:begidx] # fixed portion of the arg
arg = line[before_arg+1:endidx]
pattern = arg + '*'
completions = []
for path in glob.glob(pattern):
path = _append_slash_if_dir(path)
completions.append(path.replace(fixed, "", 1))
return completions
MyShell().cmdloop()

List returning 0 when I use extend (multiprocessing pool)

I'm trying to do a proxy checker with multiprocessing pool, and I'm getting 0 from a variable that I have to save the proxies working and the proxies that don't work but it just return 0 in both, I'm on python 3.5 debian9.6, the file has 200 lines (one proxy for each line)
#!usr/bin/env python3
from multiprocessing import Pool
import requests
import time
import sys
if (sys.version_info > (3, 0)):
pass
else:
print("This program was written for python 3")
exit()
class ProxyChecker():
def __init__(self, proxy_list_file):
self.proxy_list = proxy_list_file
self.working = []
self.not_working = []
self.time_elapsed = 0
def start_pool_to_check_proxies(self):
start_time = time.time()
with Pool(processes=200) as p:
p.map(self.check_proxies, self.proxy_list)
self.time_elapsed = time.time() - start_time
print("Number of working proxies = " + str(len(self.working)))
print("Number of proxies that don't work = " \
+ str(len(self.not_working)))
print("Number of proxies that have been checked = " + \
str(len(self.proxy_list)))
print("Time elapsed while cheking " + str(len(self.proxy_list) \
+ self.time_elapsed))
def check_proxies(self, proxy):
try:
response = requests.get(
'http://google.com',
proxies={'http': 'http://' + proxy},
timeout=25
)
print('Checking ' + proxy + " ...")
self.working.extend(str(proxy))
except Exception as e:
print("Something went wrong")
self.not_working.extend(str(proxy))
"""else:
if response.status_code == 200:
self.working.extend(proxy)
print(self.working)
else:
self.not_working.extend(proxy)"""
def main():
try:
with open("proxies.txt", 'r') as f:
proxies = f.read().split('\n')
except IOError:
print('Error opening the file')
print('Check the name of the file')
else:
# with open("proxies.txt", 'a') as f:
# f.write("*************Working Proxies*************")
checker = ProxyChecker(proxies)
checker.start_pool_to_check_proxies()
if __name__ == '__main__':
main()
As I said the idea is to save in a list how many proxies works (and which ones) but it just return 0 and the proxy_list return the proxies right.
If anyone could help me I would be so pleased.
Happy new year!!

how to run multiple .py files with infinite loop from a python module?

I have two files. Let's call it file_X.py and file_Y.py. Both have infinite loops that continuously read data from COM ports. I have a tkinter module with two buttons to launch file_X and file_Y. So if I click button A, I want file_X to run and button B would launch file_Y. How can I run these files in parallel and have them display the data in their respective command prompt terminals?
I tried using runpy and os.system. os.system would throw me an error even though the modules for both files were working fine on their own. On the other hand, runpy wouldn't let me click on the other button while the first module was running.
Tkinter module:
import tkinter as tk
import time
import runpy
root = tk.Tk()
root. title("App")
root.geometry('700x500')
v = tk.IntVar()
v.set(-1)
button_labels = [
(" Device 1 "),
(" Device 2 ")]
def ShowChoice():
choice = v.get() + 1
if(choice == 1):
runpy.run_module('file_X', run_name='__main__')
elif(choice == 2):
runpy.run_module('file_Y', run_name='__main__')
tk.Label(root,
text="""Choose the device you want to launch:""",
font = 'Arial 20 bold',
justify = tk.LEFT,
height = 6,
padx = 20).pack()
for val, button_label in enumerate(button_labels):
tk.Radiobutton(root,
text = button_label,
font = 'Times 12 bold',
indicatoron = 0,
bg = 'cornflower blue',
width = 40,
padx = 20,
pady = 5,
variable=v,
command=ShowChoice,
value=val).pack(anchor=tk.S)
root.mainloop()
file_X and file_Y have pretty much the same code but are connected to different COM Ports and have different string modifications.
import serial
import time
import csv
try:
ser = serial.Serial("COM4",
baudrate=2400,
bytesize=serial.EIGHTBITS,
parity =serial.PARITY_ODD)
except:
print("Device not detected")
def Reader():
global ser
try:
data = ser.readline().decode('utf-8')
data = str(data).replace("\r\n","")
data = data.replace("\x000","")
return data
except:
return "Data Unavailable"
def Start():
date_now = time.strftime('%d.%m.%y')
time_now = time.strftime('%H.%M.%S')
file_name = date_now + '__' + time_now + '.csv'
with open(file_name, 'w+') as f:
csv_file = csv.writer(f)
csv_file.writerow(['DATE','TIME','VALUE'])
while True:
date_now = time.strftime('%d/%m/%y')
time_now = time.strftime('%H:%M:%S')
data = Reader()
csv_file.writerow([date_now, time_now, data])
print([date_now, time_now, data])
if __name__ =='__main__':
Start()
You could use the threading, multiprocessing or subprocess modules.
Here is a quick sample which demonstrates the threading module.
import threading, time
def Start(name=''):
cnt=0
while(cnt<10):
cnt+=1
print "This is thread %s" % name
time.sleep(1)
thread1 = threading.Thread(target=Start, name='Thread-1', args=('Serial1',))
thread2 = threading.Thread(target=Start, name='Thread-2', args=('Serial2',))
thread2.start()
thread1.start()
while (thread1.isAlive() and thread2.isAlive()):
time.sleep(2)
print "Running Threads : %s" % [thread.name for thread in threading.enumerate()]
print "done"
As suggested you could import file_X and file_Y and create a thread for each using the Start() function as the target (callable object) to be invoked by the run() method of each thread.
import file_X, file_Y
thread1 = threading.Thread(target=file_X.Start, name='COM1')
thread2 = threading.Thread(target=file_Y.Start, name='COM2')
thread1.start()
thread2.start()
The multiprocessing module is similar to threading.
Alternatively run file_X and file_Y as subprocesses using the subprocess module.
NEW <<<<
Here is a solution using threading. I've only tested it with one port.
import threading
import time
import serial
import sys, os.path
import csv
def OpenSerialPort(port=""):
print ("Open port %s" % port)
serPort = None
try:
serPort = serial.Serial(port,
baudrate=2400,
bytesize=serial.EIGHTBITS,
parity =serial.PARITY_ODD)
except serial.SerialException as msg:
print( "Error opening serial port %s" % msg)
except:
exctype, errorMsg = sys.exc_info()[:2]
print ("%s %s" % (errorMsg, exctype))
return serPort
def Reader(file_name, serialPort, stopped):
print ("Start reading serial port %s." % serialPort.name)
serialPort.timeout = 1.0
while not stopped.is_set():
serData = ''
try:
#print "Reading port..."
serData = serialPort.readline()
except:
exctype, errorMsg = sys.exc_info()[:2]
print ("Error reading port - %s" % errorMsg)
stopped.set()
break
if len(serData) > 0:
serData = serData.decode('utf-8')
serData = str(serData).replace("\r\n","")
serData = serData.replace("\x000","")
Log_Data(file_name, serData)
#else:
# print("Reader() no Data")
serialPort.close()
print ("Reader finished. Closed %s" % serialPort.name)
def Init_Log(portName=''):
#Create log file
portName = os.path.basename(portName)
file_name = time.strftime('%d.%m.%y__%H.%M.%S') + "__%s.csv" % portName
with open(file_name, 'w') as f:
csv_file = csv.writer(f)
csv_file.writerow(['DATE','TIME','VALUE'])
return file_name
def Log_Data(file_name='', dataString=''):
date_now = time.strftime('%d/%m/%y')
time_now = time.strftime('%H:%M:%S')
with open(file_name, 'a') as f:
csv_file = csv.writer(f)
csv_file.writerow([date_now, time_now, dataString])
print([date_now, time_now, dataString])
if __name__ == "__main__":
stopped = threading.Event() # Create stopped event to notify all threads when it is time to stop.
#Open COM3 ports
portName = 'COM3'
serialPort_1 = OpenSerialPort(portName)
if serialPort_1 == None:
sys.exit(1)
file_name_1 = Init_Log(portName) #Create log file
p1 = threading.Thread(target=Reader, args=(file_name_1, serialPort_1, stopped,))
#Open COM4 ports
portName = 'COM4'
serialPort_2 = OpenSerialPort(portName)
if serialPort_2 == None:
sys.exit(1)
#Create log file
file_name_2 = Init_Log(portName)
p2 = threading.Thread(target=Reader, args=(file_name_2, serialPort_2, stopped,))
#Start port reader threads
p1.start()
p2.start()
#This is just a test loop that does nothing for awhile.
loopcnt = 20
while (loopcnt > 0) and (not stopped.is_set()):
loopcnt -= 1
print ("main() %d" % loopcnt)
try:
time.sleep(1)
except KeyboardInterrupt: #Capture Ctrl-C
print ("Captured Ctrl-C")
loopcnt=0
stopped.set()
stopped.set()
print ("Stopped")
p1.join()
p2.join()
serialPort_1.close()
serialPort_2.close()
print ("Done")

Python permission error unskippable

I'm trying to make an antivirus in python, but I keep getting a permissions denied error when i get its hash and check even when I make it ignore the error and try and move on to the next file to hash and check. I'm fine with the error, but I'm trying it to make it move to the next file and nothing I try works. I'm using windows.
AV.py
#!/usr/bin/python3.5
import os
import sys
import time
import glob
import simple_hasher
from colorama import *
init()
#Begin code
#variable_set
virlfile = "ListFile.hash"
vircount = 0
virusdel = []
hashtype = "MD5"
#variable_end
#fileloadhash
if not os.path.isfile(virlfile):
try:
with open(virlfile, "w") as f:
f.close
except IOError as err:
print("Error, Something went WRONG!")
print("Error as reported:")
print("{}".format(err))
with open(virlfile) as f:
data = f.read()
#scanner
filecount = 0
try:
for file in glob.glob("./**/*", recursive = True):
if os.path.isfile(file):
file_hash = simple_hasher.get_hash(file, hashtype)
if file_hash in data:
print("{} | {}".format(file_hash, Fore.CYAN + file + " (!)ALERT" + Style.RESET_ALL))
vircount += 1
virusdel.append(file)
filecount += 1
else:
print("{} | {}".format(file_hash, file))
filecount += 1
except OSError:
pass
if vircount > 0:
print("\n{} Viruses Detected. Delete? Y/N".format(vircount))
try:
choice = input(">> ").lower().split(" ")
except KeyboardInterrupt:
print("SCAN ABORTED!")
try:
if choice[0] == "y":
for file in virusdel:
try:
os.remove(file)
print("File Deleted - {}".format(os.path.abspath(file)))
except Exception as err:
print ("Unable to remove file.\n{}".format(err))
print("\n(+) All Viruses Removed.\n")
else:
sys.exit()
except Exception as err:
print("Error: {}".format(err))
else:
print("\n(+)No viruses\n")
sys.exit()
I also have a custom module being imported:
simple_hasher.py
import hashlib
import os
import sys
def get_hash(file, ver):
if ver.lower() == "md5":
h = hashlib.md5()
elif ver.lower() == "sha1":
h = hashlib.sha1()
elif ver.lower() == "sha256":
h = hashlib.sha256()
else:
h = hashlib.sha1()
while not False:
try:
with open(file, "rb") as f:
while True:
data = f.read(2 ** 20)
if not data: break
h.update(data)
return h.hexdigest()
except Exception as err:
print("[Debug] [{}] - Message: {}".format(os.path.split(__file__)[1], err))
pass
The error:
[Debug] [simple_hasher.py] - Message: [Errno 13] Permission denied: '.\\hiberfil.sys'

Resources