How come my python batch file closes once its done? - python

Im trying to prevent the cmd to close when script is done and print out the message and wait for the users input and THEN close but it just closes as soon as its done.. what am I doing wrong?
except tweepy.TweepError as e:
print(e.reason)
sleep(10)
continue
except StopIteration:
break
print('Automation Done! ' + number + ' times! Press Any Key To Continue...')
input()

If it is a batch file, (with a .bat and not a .py) you can use
pause
or
pause >nul
EDIT:
pause
This will prompt the user for input, upon pressing any key, it will proceed.
pause >nul
This will not prompt the user for input, however, it will still behave the same as the regular pause

If you use os.system("pause"), the application send to operational sistem to pause the execution. This code can solve your problem:
import os
# Code...
except tweepy.TweepError as e:
print(e.reason)
sleep(10)
continue
except StopIteration:
print('Automation Done! ' + number + ' times!')
os.system("pause")

Related

How to make python loop interruptible by ^C on unix?

I've written a python script that looks up the recommended server at nordvpn.com and starts the according vpn. There is a part in this script where I assure there is internet access. When I run the script from a terminal, I cannot interrupt this loop by pressing ^C if there is no connection. How can I adapt the code so that the loop is interruptible?
Here is relevant part of the code:
#!/usr/bin/env python3
import re
import os
from selenium import webdriver
if __name__ == '__main__':
# ...
# wait for internet connection and load geckodriver
while True:
try:
browser = webdriver.Firefox(
executable_path=r'/home/maddin/bin/.vpn/geckodriver',
log_path='/dev/null')
break
except:
print("not connected yet, trying again....")
# ...
Using except: will catch all errors, including KeyboardInterrupt. You can instead use except Exception: which will not catch SystemExit, KeyboardInterrupt and GeneratorExit. This will allow you to break a loop with Ctrl + C. You can find more information here and here.
this is because of your default except block which takes all Interrupts including KeyboardInterrupt which is your ^C
while True:
try:
browser = webdriver.Firefox(
executable_path=r'/home/maddin/bin/.vpn/geckodriver',
log_path='/dev/null')
break
except KeyboardInterrupt:
# do whatever you want to do on ^C
except:
print("not connected yet, trying again...."

How to point from one module to the next

I'm trying to make a password system for a program. I have the first half working so when I punch in the code it opens my file. After that the program asks for the password again instead of moving on to the next module which is supposed to close the file. Here's what I have
import os
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
except Exception as e:
print (str(e))
while True:
choice = int(input("Close? (y/n): "))
if (choice<='y'):
if choice =='y':
os.system('TASKKILL /F /IM C:\\restriced access')
I want it to kind of appear as an "if/then" kinda statement. For example if the password is entered correctly it opens the file `os.startfile('C:\restriced access') then points to the next module to give the option to close.
"While True" just keeps looping infinitely. As soon as you open the file it'll go back to the beginning of that loop and ask for your password again. If you want it to break from that loop if they get the password correct you need to add a "break" after your startfile line. I'm also not sure why you check their password twice. If you want it to exit the loop after attempting to open the file whether it succeeds or not, add a "finally" block after your exception handler.
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
Your while loop is while True:. This will never exit unless you explicitly exit from it. You want to add a break in it like so:
os.startfile('C:\\restriced access')
break
Great to see you learn python.
The reason is because the while loop doesn't have a break in it.
Then again avoid opening files in a loop.
Also the nested if makes it hard to debug.
Also checkout pep8.
havent made any code changes.
import os
while True:
choice = int(input("Enter Password: "))
if (choice<1124):
continue
if choice ==1124:
try: os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
break
while True:
choice = input("Close? (y/n): ")
if (choice=='y'):
break

Can not get keyboardInterrupt to catch ctrl c in python program running in linux

I want my program to stop executing when a ctrl-c is entered in the terminal window (that has focus) where the program is executing. Every google hit tells me this should work but it doesn't.
First I tried putting the try block in a class method my main invoked:
try:
for row in csvInput:
<process the current row...>
except KeyboardInterrupt:
print '\nTerminating program!\n'
exit()
and then I tried putting the try block in my main program and that didn't work:
if __name__ == '__main__':
try:
programArg = ProgramArgs(argparse.ArgumentParser)
args = programArg.processArgs()
currentDir = os.getcwd()
product = Product(currentDir, args.directory[0], programArg.outputDir)
product.verify()
except KeyboardInterrupt:
print '\nTerminating program!\n'
exit()
I recently (May 2, 2020) hit this same issue in Windows-10 using Anaconda2-Spyder(Python2.7). I am new to using Spyder. I tried multiple ways to get [break] or [ctrl-c] to work as expected by trying several suggestions listed in stackoverflow. Nothing seemed to work. However, what I eventually noticed is that the program stops on the line found after the "KeyboardInterrupt" catch.
[Solution]: select [Run current line] or [continue execution] from the debugger tools (either menu item or icon functions) and the rest of the program executes and the program properly exits. I built the following to experiment with keyboard input.
def Test(a=0,b=0):
#Simple program to test Try/Catch or in Python try/except.
#[break] using [Ctrl-C] seemed to hang the machine.
#Yes, upon [Ctrl-C] the program stopped accepting User #
Inputs but execution was still "hung".
def Add(x,y):
result = x+y
return result
def getValue(x,label="first"):
while not x:
try:
x=input("Enter {} value:".format(label))
x = float(x)
continue
except KeyboardInterrupt:
print("\n\nUser initiated [Break] detected." +
"Stopping Program now....")
#use the following without <import sys>
raise SystemExit
#otherwise, the following requires <import sys>
#sys.exit("User Initiated [Break]!")
except Exception:
x=""
print("Invalid entry, please retry using a " +
"numeric entry value (real or integer #)")
continue
return x
print ("I am an adding machine program.\n" +
"Just feed me two numbers using "Test(x,y) format\n" +
"to add x and y. Invalid entries will cause a \n" +
"prompt for User entries from the keyboard.")
if not a:
a = getValue(a,"first")
if not b:
b = getValue(b,"second")
return Add(a,b)

Python script does not restart after it crashes

I have a python script that is doing some stuff called "python1.py". Sometimes because connection issue, it crashes. I have another script called "loop.py" that is supposed to monitor the first one when it crashes and restart it. So far, it fails to restart. Meaning, when an exception is risen ( IOError or WatsonException ( I am using a Watson API ) ) the script stops
python1.py is something like this :
def mainfunction ():
a = randrange(0, 1)
Print (' my routine is doing something')
if a = 1 :
Print ('a = 1 ')
else :
Print (' a is not equals to 1')
mainfunction ()
The other script that is supposed to restart the first one is something like this :
def loopApp():
while True :
try:
python1.mainfunction ()
except IOError :
print (' IOError y')
except WatsonException :
print (' Exception from watson API')
loopApp ()
python1.py should restart when every time the exceptions happens, but it is not.
I found the way using python subprocess. It works fine and I could get expections working.
def loopApp():
loop = 1
while loop == 1:
print ("wa_loop is starting")
try:
process = subprocess.call(['python', 'wa_dir_watch.py'])
except 'IOError':
print ("\nretrying after IOError")
continue
except KeyboardInterrupt:
print ("\nstopped by user Ctr+C")
quit()
loopApp()

Code not running after os.system call

In this code
while 1:
try:
#print "try reading socket"
os.system("echo 1 >/sys/class/leds/led0/brightness")
data, wherefrom = s.recvfrom(1500, 0) # get the data from the socket
except (KeyboardInterrupt, SystemExit):
#print "reraise error"
raise
except timeout:
print "No data received: socket timeout"
#print sys.exc_info()[0]
break
except:
print "Unknown error occured with receiving data"
break
print (data + " " + repr(wherefrom[0]))
if (data.find("Start SID" + myserial[-4:]) != -1):
os.system('sudo python /home/pi/simplesi_scratch_handler/scratch_gpio_handler2.py '+ str(repr(wherefrom[0])))
for i in range (0,20):
os.system("echo 0 >/sys/class/leds/led0/brightness")
time.sleep(0.5)
os.system("echo 1 >/sys/class/leds/led0/brightness")
time.sleep(0.5)
break
os.system("echo mmc0 >/sys/class/leds/led0/trigger")
s.close()
sys.exit()
the code after
os.system('sudo python /home/pi/simplesi_scratch_handler/scratch_gpio_handler2.py '+ str(repr(wherefrom[0])))
doesn't seem to run (the code blinks an LED and this doesn't happen - if I put the blink code befoer the os.system call then it works)
Can I get python to launch a new terminal/shell and run my 2nd python prog in that?
regards
Simon
modify your sudoers file (with the visudo command) to add this line
myusername ALL=(ALL:ALL) NOPASSWD:/home/pi/simplesi_scratch_handler/scratch_gpio_handler2.py
Where "myusername" is the user name that you intend to run the program as
You also mentioned you would like to run the system program in a new shell?
os.system('sudo python /home/pi/simplesi_scratch_handler/scratch_gpio_handler2.py '+ str(repr(wherefrom[0])) + " &")
runs the program in such a way that the shell it starts does not block the process that starts it.
Hope this helps

Categories

Resources