I am trying to improve a code I found online so that it doesn't waste so much paper.
The files I will be printing are small labels which do not take a lot of space. I would like to be able to "merge" those labels so that they'd be printed out by groups of 6 per page.
This is the code (it already has some modifications):
# Import libraries
import os
from pickle import TRUE
import time
import tkinter as tk
from tkinter import filedialog
def menu():
print("1- Retry")
print("0- Exit")
s=TRUE
while s:
opt = input("Select an option: ")
try:
if int(opt) == 1 or int(opt) == 0:
opt = int(opt)
s = False
except:
input("Press enter to try again.")
return opt
s = TRUE
while s:
root = tk.Tk()
root.withdraw()
path = filedialog.askdirectory()
try:
# Extracting all the contents in the directory corresponding to path
l_files = os.listdir(path)
# Iterating over all the files
for file in l_files:
# Instantiating the path of the file
file_path = f'{path}\\{file}'
# Checking whether the given file is a directory or not
if os.path.isfile(file_path):
try:
# Printing the file pertaining to file_path
os.startfile(file_path, 'print')
print(f'Printing {file}')
# Sleeping the program for 5 seconds so as to account the
# steady processing of the print operation.
time.sleep(5)
except:
# Catching if any error occurs and alerting the user
print(f'ALERT: {file} could not be printed! Please check\
the associated softwares, or the file type.')
else:
print(f'ALERT: {file} is not a file, so can not be printed!')
s = False
except:
print('No folder selected.')
opt = menu()
if opt == 0:
break
else:
pass
print('Task finished!')
Related
I'm trying to write a code a that gets user input via pop up and use that in different program.
below is the code which gets user input.
Excel_connection.py
import openpyxl
import tkinter as tk
class App(tk.Frame):
def __init__(self,master=None,**kw):
#Create a blank dictionary
self.answers = {}
tk.Frame.__init__(self,master=master,**kw)
tk.Label(self,text="Give Input Sheet Path").grid(row=0,column=0)
self.Input_From_User1 = tk.Entry(self)
self.Input_From_User1.grid(row=0,column=1)
tk.Button(self,text="Feed into Program",command =
self.collectAnswers).grid(row=2,column=1)
def collectAnswers(self):
self.answers['Input_Path'] = self.Input_From_User1.get()
global Input_Path
Input_Path = self.answers['Input_Path']
functionThatUsesAnswers(self.answers)
quit()
def quit():
root.destroy()
if __name__ == '__main__':
root = tk.Tk()
App(root).grid()
root.mainloop()
wb = openpyxl.load_workbook(Input_Path) # trying to open the open the input sheet from the
below path
ws = wb["Sheet1"]
Below is the code where i'm importing the above program which does some operation
Execution.py
import pandas
from Excel_Connection import *
from Snowflake_Connection import *
all_rows = list(ws.rows)
cur = ctx.cursor()
# Pull information from specific cells.
for row in all_rows[1:400]:
scenario = row[1].value
query = row[2].value
if_execute = row[3].value
if if_execute == 'Y':
try:
cur.execute(query)
df = cur.fetch_pandas_all()
except:
print(scenario," Failed")
else:
print("CREATED",scenario,".csv successfully")
print("ALL INDIVDUAL REPORT GENERATED")
When I'm executing Execution.py, the program does not produce pop up window and instead the code throws below error,
wb = openpyxl.load_workbook(Input_Path) # trying to open the open the input sheet from the below path
NameError: name 'Input_Path' is not defined
I tried to -
executing Excel_connection.py separately and it just worked fine.
place the code directly instead of importing the program in the Execution.py and again it worked fine as expected.
The only time I'm facing issue is when I try to import the Excel_connection.py into Excel_connection.py
Could somebody kindly help me out here.
When you import Excel_connection.py, it'll run the code in it.
So as you run Execution.py:
import pandas -> "run" the pandas stuff to define functions, etc...
from Excel_connection import * -> You import everything from Excel_connection. So the interpreter will open this file, parse, and run:
2.1 Class App is defined
2.2 runs: wb = openpyxl.load_workbook(Input_Path), which is a nonsense. Since as I see Input_Path is defined in App.collectAnswers(), which was never executed before. So there is no Input_Path to use... And you program terminates here, and tells you that.
If you run your Excel_connection.py directly, it'll work, because the if __name__ == '__main__' is True in this case and that section runs too. But if you import the file, it is false so you skip that part of the code.
You should move this to the Execution.py file before the all_rows = list(ws.rows) line
wb = openpyxl.load_workbook(Input_Path) # trying to open the open the input sheet from the
below path
ws = wb["Sheet1"]
And it'll still break since we have no Input_Path, so you must define it somehow, but it is up to you how. You can create an App like how you do it in the Excel_connection.py.
But I shouldn't do that since it is a little ugly. I would do something like:
Excel_Connection.py
import openpyxl
import tkinter as tk
class App(tk.Frame):
def __init__(self,master=None,**kw):
#Create a blank dictionary
self.answers = {}
tk.Frame.__init__(self,master=master,**kw)
tk.Label(self,text="Give Input Sheet Path").grid(row=0,column=0)
self.Input_From_User1 = tk.Entry(self)
self.Input_From_User1.grid(row=0,column=1)
tk.Button(self,text="Feed into Program",command =
self.collectAnswers).grid(row=2,column=1)
def collectAnswers(self):
self.answers['Input_Path'] = self.Input_From_User1.get()
global Input_Path
Input_Path = self.answers['Input_Path']
functionThatUsesAnswers(self.answers)
self.quit()
# def quit():
# root.destroy()
def main():
root = tk.Tk()
App(root).grid()
root.mainloop()
wb = openpyxl.load_workbook(Input_Path) # trying to open the open the input sheet from the below path
return wb["Sheet1"]
if __name__ == '__main__':
main()
and then
Execution.py
import pandas
import Excel_Connection
from Snowflake_Connection import *
# Now we call the main() function from Excel_Connection, which will return the worksheet for us.
ws = Excel_Connection.main()
all_rows = list(ws.rows)
cur = ctx.cursor()
# Pull information from specific cells.
for row in all_rows[1:400]:
scenario = row[1].value
query = row[2].value
if_execute = row[3].value
if if_execute == 'Y':
try:
cur.execute(query)
df = cur.fetch_pandas_all()
except:
print(scenario," Failed")
else:
print("CREATED",scenario,".csv successfully")
print("ALL INDIVDUAL REPORT GENERATED")
you can simply use
csv files
or some file format like that to store and transfer data between files.
My program works fine but when it finished gives error like that :
could not convert to integer . Path ' exitCode'. value too big or too small for Int32
Python 3.7
from re import compile
from os import path, walk
from pywinauto import win32api
from easygui import fileopenbox
from pyautogui import confirm, alert
from sys import exit
def Find_Client_Path():
file_name = compile("LeagueClient.exe")
for driver in win32api.GetLogicalDriveStrings().split("\000")[:-1]:
for root, folders, files in walk(driver):
for file in files:
find_file = file_name.search(file)
if find_file:
return path.join(root, file)
return Find_Path_Manually()
def Find_Path_Manually():
alert(
"Please select LeagueClient.exe in Riot Games / League of Legends /.",
title="Warning",
button="Okay",
)
path = fileopenbox()
if path.find("LeagueClient.exe") != -1:
return path
else:
secim = confirm(
"You choose the worng file. Please select LeagueClient.exe in Riot Games / League of Legends / . If you want to close bot click EXIT button.",
title="UYARI!",
buttons=("OKAY", "EXIT"),
)
if secim == "EXIT":
sys.exit()
elif secim == "OKAY":
return Find_Path_Manually()
This is my Program, Text Extraction from Image program:
import pytesseract
from PIL import Image
import os
from os.path import join
import sys
con_1 = True
store_1 = []
store_2 = []
store_3 = []
con_1 = True
print("Welcome to my Text Extraction from Image Program. Here you can extract text from any image.")
while con_1:
image_name = input("Enter your image's name:")
for root, dirs, files in os.walk("/home/"):
if image_name in files:
found = join(root, image_name)
store_1.append(found)
if len(store_1) == 0:
ask_1 = str(input("Your image was not found. Do you want to try again(Y/n)?:"))
if ask_1 == "Y" or ask_1 == "y":
con_1 = True
elif ask_1 == "N" or ask_1 == "n":
con_1 = False
else:
print("Your input is out of bounds. Please try again.")
else:
print("Your image was successfully found.")
image_open = Image.open(found)
image_text = pytesseract.image_to_string(image_open)
print(image_text)
break
This is the image I am testing it on:
And this is the most weirdest output I have ever seen:
‘Understanding how computer memory
ia tire terrae tec
programming lan
This is another image I am testing it on:
And another really weird output:
Sesh chee nia ec Hiok pc
RU hun oe
mete een
machines work while still being easy to learn.
I have never seen my program giving me such off-target and weird outputs. I have absolutely no idea how this is happening. I would very much like to know how to fix it as well as why my program is malfunctioning.
This is a simple script that is used to calculate Z scores of some neuropsychological tests.
But recently the code seems to be running on the background even after exiting the program. This problem didn't exist before, I use the following startup piece to ensure program is running with elevation, and is correct size for the display.
Program can be shut down using a "exit" command that raises SystemExit or just by pressing the X button on the top bar. Program keep running on the background regardless.
Where did I go wrong?
def progStructure():
first_run = True
if first_run:
import os
os.system("mode con: cols=160 lines=50")
print("""
================================================
PROGRAM GREETING
================================================
""")
mainStartup()
first_run = False
while settings("auto_run"):
mainStartup()
#this function contains the main program, but irrelevant to the question
print("Auto shutdown enabled, program is shutting down.")
wait(2)
exit()
#informs the user data has been saved then restarts
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
progStructure()
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, "", None, 0)
progStructure()
My excel writing function:
def excelWriter(excel_path, data_num, printable_list):
from time import strftime
date = strftime("%Y-%m-%d")
time = strftime("%H:%M:%S")
if settings("excel_output_subjectNames"):
patient_name_local = patient_name
else:
patient_name_local = "N/A"
demographic_data = [patient_ID, patient_name_local, patient_admin, date, time, patient_age, patient_sex, patient_edu]
from openpyxl import Workbook
from openpyxl import load_workbook
wb = Workbook(write_only=False)
try:
test_name_list = [
"(1)MMT", "(2)MOCA", "(3)3MS", "(4)GISD", "(5)ECR",
"(6)Sözel Bellek Süreçleri", "(7)Rey Karmaşık Figür", "(8)İz Sürme", "(9)Stroop",
"(10)Wisconsin", "(11)Görsel Sözel Test", "(12)Renkli İz Sürme",
"(13)Wechsler", "(14)Wechsler-Sayı Dizisi", "(15)Sözel Akıcılık",
"(16)Semantik Akıcılık", "(17)Saat Çizme", "(18)SDOT", "(19)Ayları İleri-Geri Sayma"
]
while True:
try:
data_workbook = load_workbook(filename = excel_path + settings("excel_name"), read_only=False)
active_sheet = data_workbook.get_sheet_by_name(test_name_list[data_num-1])
active_sheet.append(demographic_data + printable_list)
data_workbook.save(filename = excel_path + settings("excel_name"))
break
except:
for i in range(len(test_name_list)):
wb.create_sheet(title = test_name_list[i])
wb.save(filename = excel_path + settings("excel_name"))
data_workbook = load_workbook(filename = excel_path + settings("excel_name"), read_only=False)
active_sheet = data_workbook.get_sheet_by_name("Sheet")
data_workbook.remove_sheet(active_sheet)
data_workbook.save(filename = excel_path + settings("excel_name"))
continue
except:
raise
Forgot to close the excel file after writing, that seemingly fixed the problem, thanks for everyone helping out.
I made a script which is suppose to use Tkinter to allow to choose and load files and store their content in different objects and then process each of these documents.
I would like to make the script able to process only a certain amount of documents determined by a question (the value is stored under "File_number")
For exemple: if at the question "how many files do you want to compare?"
the user enter 3
I would like the tkinter openfile window to ask only for 3 files then keep going
I am using the If Else statement like below
but it doesn't seem to work well and the code is really not pythonic.
Is there a better/shorter way to perform the same?
Thanks
My script look like this
import pandas as pd
from pandas import *
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
import pylab
import pandas.io.data
import os
import Tkinter
from Tkinter import *
import tkFileDialog
import tkSimpleDialog
from tkFileDialog import askopenfilename
import sys
# Set up GUI
root = Tkinter.Tk(); root.withdraw()
# Prompt for user info
File_number = tkSimpleDialog.askinteger("File number", "How many files do you want to compare?")
# Prompt for file explorer
# Also extract the file_name
process_a = 0
if process_a = File_number:
break
else:
process_a = process_a + 1
fileloc1 = tkFileDialog.askopenfilename(parent=root, title='Choose file 1')
fileloc1_name_clean = os.path.splitext(fileloc1)[0]
fileloc1_name = os.path.basename(fileloc1_name_clean)
if process_a = File_number:
break
else:
process_a = process_a + 1
fileloc2 = tkFileDialog.askopenfilename(parent=root, title='Choose file 2')
fileloc2_name_clean = os.path.splitext(fileloc2)[0]
fileloc2_name = os.path.basename(fileloc2_name_clean)
if process_a = File_number:
break
else:
process_a = process_a + 1
fileloc3 = tkFileDialog.askopenfilename(parent=root, title='Choose file 3')
fileloc3_name_clean = os.path.splitext(fileloc3)[0]
fileloc3_name = os.path.basename(fileloc3_name_clean)
EDIT 1
The next part of my script is:
dfa_1 = pd.read_csv(fileloc1, delimiter='\t')
dfa_nodupli = dfa_1.drop_duplicates(cols='N', take_last=False)
dfa_nodu_2pep = dfa_nodupli[(dfa_nodupli['Peptides(95%)'] > 1)]
dfa_nodu_2pep = dfa_nodu_2pep[~dfa_nodu_2pep['Name'].str.contains('Keratin')]
dfa_nodu_2pep.to_csv(fileloc1_name + ".csv")
dfb_1 = pd.read_csv(fileloc2, delimiter='\t')
dfb_nodupli = dfb_1.drop_duplicates(cols='N', take_last=False)
dfb_nodu_2pep = dfb_nodupli[(dfb_nodupli['Peptides(95%)'] > 1)]
dfb_nodu_2pep = dfb_nodu_2pep[~dfb_nodu_2pep['Name'].str.contains('Keratin')]
dfb_nodu_2pep.to_csv(fileloc2_name + ".csv")
I modified your code, so that it works, in a way you want it ( I hope).
import Tkinter
import tkFileDialog
import tkSimpleDialog
from tkFileDialog import askopenfilename
import os
# Set up GUI
def main():
root = Tkinter.Tk();
root.withdraw()
# Prompt for user info
File_number = tkSimpleDialog.askinteger("File number",
"How many files do you want to compare?")
if not File_number:
return
user_fiels = []
max_file_no = int(File_number)
current_file = 1;
while(current_file <= max_file_no):
fileloc = tkFileDialog.askopenfilename(parent=root, title='Choose file {}'.format(current_file))
if not fileloc:
continue
fileloc_name_clean = os.path.splitext(fileloc)[0]
fileloc_name = os.path.basename(fileloc_name_clean)
user_fiels.append([fileloc, fileloc_name_clean, fileloc_name])
current_file += 1
#print(fileloc_name_clean, fileloc_name)
print(user_fiels)
main()
I use while loop to get file paths as many times as you want.