If in a function not working if Boolean value is false - python

HELO
I am new to Python and learning a lot thanks to Stackoverflow, but at the moment I am stuck at this simple task where I was sure I would resolve it myself but spent few hours looking around.
I have Tkinter GUI with a button, where if pressed it will look for such name in specific file path and if it finds "Check For Updates", it will run it else it will do nothing as expected.
import tkinter as tk
import os
root = tk.Tk()
button = tk.Button(root, text="Open", height=1, width=25, borderwidth="2", command=lambda: openupdt())
button.grid()
def openupdt():
os.startfile(r"C://ProgramData//Microsoft//Windows//Start Menu//Programs//Java//Check For Updates")
root.mainloop()
Here I tried to use IF statement but it seems like I am doing something wrong. If no file in such path is found I would like it to print message or do what ever is instructed.
def openupdt():
os.startfile(r"C://ProgramData//Microsoft//Windows//Start Menu//Programs//Java//Check For Updates")
if openupdt == False:
print("No such file")
gives me an error "The system cannot find the file specified:" as if it fully ignores IF statement
Thank you.

If you want to check, if something with certain path exists or not, use os.path.exists that returns true or false. In your case, it might be like
import os
def openupdt():
if os.path.exists("/your/path"):
do_something()
else:
print("No such file or directory")
The main problem in your code is fact that in if statement you compare False with openupdt, but your function name is openupdt. You are actually comparing function to bool value, that's incorrect. Better make use of os.path.exists like I provided above and this will work for you.

You should first check if the file exists and then use the os.startfile.
Try something like:
if os.path.isfile("your_path_to_file"):
os.startfile("your_path_to_file")
else:
print("No such file")
You can also use try...except and handle the error as it appears:
try:
os.startfile("your_path_to_file")
except FileNotFoundError:
print("No such file")

The main thing is that you should be using a try-except for os.startfile(). Additionally your if statement is checking the function instead of a variable which makes the comparison not viable. Plus you are using a raw string literal so you don't need the extra slashes.
def openupdt():
try:
os.startfile(r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Java\Check For Updates")
except:
print("No such file")

Related

only one if statement is not working all of sudden. Please take a look

I am writing a code that executes commands that were inputted by users. Among the codes, my 1st elif statement is not working. It is supposed to open a file dialog so that the user can browse through files to get the one that is needed. It worked just fine like a moment ago and but when I ran it after deleting some lines and making some changes to the names of the functions (to make the code look better), it does not work all of a sudden. It opens filedialog, yes, but it does not import the file selected to the python any more. What may be the cause of this? The code looks like below:
import pandas as pd
import tkinter.filedialog
def Assign():
# do work
return audit_assignment()
def audit_assignment():
while True:
command = input('Enter command here: ')
if command not in {"1","2","3","4","5","6","7"}:
print('That is not a valid entry. Please enter a integer value from one through
seven.')
elif command == "1":
Mydf=pd.read_csv(tkinter.filedialog.askopenfile(mode='r'))
print('File successfully opened')
Assign()
of course this code goes until elif command == "7": but I think the rest is not necessary here.
I also just figured out that when I stop debugging, the selected file comes into the python, to Mydf, immediately.

Program checks if file exists before it is created

I have a problem with a code i'm writing. One of it's parts is responsible for creating a file, and it is also supposed to tell me if it was successful. If not, it should inform me as well, but the problem is - it checks if the file exists before it gets created. I tried to make a break between creation of file and checking if it exists by using time module (specifically time.sleep option, inserted in almost every place possible), but with no results. I also tried to use another way to check if the file exists. It didn't help. Whole thing works fine (excluding this part), because if the file is already there and i tell the program to create it, it tells me that it was successful, so it can read it properly, but it's too fast. I attached part of my code down below. Thank you in advance.
First way i tried, using os module:
path = 'D:\screen'
os.chdir(path)
exists = os.path.isfile('.\screenshot.png')
exists2 = os.path.isfile('.\screenshot2.png')
And here's the execution part:
def printer():
pyautogui.screenshot('D:\SCREEN\screenshot.png')
time.sleep(3)
if exists:
print("Screenshot was created successfully")
else:
print("Screenshot was not created successfully")
def printer2():
pyautogui.screenshot('D:\SCREEN\screenshot2.png')
time.sleep(3)
if exists2:
print ("Screenshot was created successfully")
else:
print ("Screenshot was not created successfully")
Second way i tried, using pathlib:
path = 'D:/screen'
file1 = Path("D:/screen/screenshot.png")
file2 = Path("D:/screen/screenshot2.png")
And the execution part:
def printer():
pyautogui.screenshot('D:/SCREEN/screenshot.png')
time.sleep(3)
if file1.isfile():
print("Screenshot was created successfully")
else:
print("Screenshot was not created successfully")
def printer2():
pyautogui.screenshot('D:/SCREEN/screenshot2.png')
time.sleep(3)
if file2.isfile():
print("Screenshot was created successfully")
else:
print("Screenshot was not created successfully")
Those variables (file1, file2) were assigned before creating the screenshot, hence they dont exist. screenshot actually returns a PIL image object. So you can check if without even using os.
def printscreen():
try:
image = pyautogui.screenshot('D:/SCREEN/screenshot.png')
except Exception as e:
print(f'Exception occured during screenshotring {str(e)}')
If you want to still check with os if they exist, use it after the screenshot.
pyautogui.screenshot('D:/SCREEN/screenshot.png')
assert os.file.exist('D:/SCREEN/screenshot.png')
I have no idea what pyautogui.screenshot() does but here goes:
Assuming that the first half of each attempt is executed before the printer functions are called, you are storing the result of os.path.isfile() before you've created the file you are testing.
You should also pick a case for the folder name, really it should be in a variable so that you are not typing it twice. You should also use os.path.join instead of typing directory separators.
In printer and printer2 of the first half you should be able to change exists/exists2 to a call to os.path.isfile().
In the simple case this should work:
def printer():
pyautogui.screenshot('D:\screen\screenshot.png') #assume this attempts to create a file
if os.path.isfile('.\screenshot.png'):
print("Screenshot was created successfully")
else:
print("Screenshot was not created successfully")
path = 'D:\screen'
os.chdir(path)
printer()
Welcome to SO!
The best to check if the file exists or not is using a try/catch block.The problem in the code is that their is a race condition between the line os.path.isfile('.\screenshot.png') and the if exists part.
You can try to use the following -
try:
fh = open('.\screenshot.png', 'rw'):
# Do something
except FileNotFoundError:
print("File not found")
Thank you for all of your answers. I was able to deal with my problem by using the solution proposed by Zonyl. It looks like the reason standing behind it was trivial(,,Those variables (file1, file2) were assigned before creating the screenshot" ,,Assuming that the first half of each attempt is executed before the printer functions are called, you are storing the result of os.path.isfile() before you've created the file you are testing.") but i'm thankful you helped me anyway. I hope another newbie in the future may find it useful.

how to check if any program is running in windows using python

I would like to use win32 in python to create 2 functions... 1. A function that checks if a certain application is running. 2. A function that checks if an application is installed...
I have tried the following to check if something is running;
def IsRunning(ProgramName):
if win32ui.FindWindow(None, ProgramName):
print("its running")
return True
else:
print("its not running!")
but the findwindow always throws an error if the program is not running before my program ever gets to the else statement and I do not know how to bypass that....
I needed to pass it like this;
def IsRunning(WindowName):
try:
if win32ui.FindWindow(None, WindowName):
print("its running")
return True
except win32ui.error:
print("its not running!")
return False
You need to put the window title exactly for it to pass the test and return True...
The next thing I want to write is a similar function that uses regular expressions to find any part of a title name...
Brilliant!!! Happy now :)
The only thing with this, is that if the Applications creator decides to change the title of the main window of the program you are trying to test for, it will no longer work... I was hoping for a much more robust way of doing it... i.e. through some kind of unique process code!
in any case this will do for the time being, but if anyone has a more definitive answer please let me know...

How do you go back to your main script after an import

I'm creating a script and have sucsessfully called on a second one, however, when the second one completes. The program just crashes - is it possible so after the import script section as completed, it will then continue back on the main script.
E.G.
My main one, which is titled Login_MainMenu.py as this script in:
if command == ('caesar'):
import os
os.system('caesarCipher.py')
time.sleep(2)
print("Your task is now completed")
sys.exit()
I'm assuming I'd have to put something at the end of caesarCipher.py, which for now is:
mode = getMode()
message = getMessage()
key = getKey()
print("\nYour translated text is: ")
print(getTranslatedMessage(mode, message, key))
Anyone got any ideas on how to do it?
Thank you.
There's nothing you have to do to return back. If it's crashing, you have a bug somewhere, but since you didn't tell us what the error message was, there's no way to help you.
However, you should not be running your other script via os.system. Import it and call its functions directly.
import caesarCipher
caesarCipher.get_translated_message()
assuming you've put the code into a function called get_translated_message, anyway.

GUI freezing when shutil copy files

def creabackuno():
startbar()
messagebox.showinfo( "Wait..","I am creating the backup, please wait...")
try:
copytree(path,r"backup\dirbackup1\.minecraft")
messagebox.showinfo( "OK!","Backup (1) created!")
stopbar()
except OSError as exc:
messagebox.showerror( "Nope!","There is already a backup to restore")
stopbar()
I have a problem with a progressbar:
The startbar() start the progressbar on the graphic interface, but when start shutil(copytree(path,r"backup\dirbackup1.minecraft")) the interface freezing and the progressbar stop until it finished.
thanks
i'm using python 3.3
sorry for my poor english
What does the progress bar show? If you are trying to show the percent of the file copied then you have to get the total length/bytes of the file first and then update periodically with the number of bytes copied. That would require using "after" to check the size of the copy-to file every so many milliseconds (I think as I am just guessing here, but search first as there has to be someone who has already done something like this.) This is the first link that I found https://mail.python.org/pipermail/tkinter-discuss/2010-December/002613.html It may be more than you want but should help.
copytree is a synchronous function, so all code execution will stop until it's done. Although tkinter is sad not to be thread-safe I recommend that you put that command in another thread:
from thread import start_new_thread as snt
#from _thread import start_new_thread as snt for python 3
def copy(onError,onEnd):
try: copytree(path,r"backup\dirbackup1\.minecraft")
except:
onError()
return
onEnd()
def onEnd():
messagebox.showinfo( "OK!","Backup (1) created!")
stopbar()
def onError():
messagebox.showerror( "Nope!","There is already a backup to restore")
stopbar()
#then call with
snt(copy,(onError,onEnd))
Execs onError if it fails and onEnd on success.
use self.Frame.update_idletasks() after every self.pgBar.step(x) statement,where 'x' stands for the value by which progressbar's value increases

Categories