Restart Python script if finish or crash Windows - python-2.7

Now I have a infinite loop in my code for the script restart when finish. The problem is when script crash.
How I can restart script if crash?
infiniteloop.py
while True:
execfile("abc.py")
abc.py
print "1"
error

Do like this,
while True:
try:
execfile("abc.py")
except Exception as e:
print "Exception occured: ", e

There's probably not any way to have the script restart itself once it's crashed, but you could add some error handling like so:
while True:
try:
execfile("abc.py")
except:
pass
Alternatively, you could use shell scripting to run your wrapper repeatedly.

Related

Is subprocess.Popen actually running or doing anything

I have am currently running subprocess.Popen as below but in some cases I think it doesn't run properly
bash_command = '/var/www/venv/bin/newrelic-admin run-python manage.py message_listener'
path_to_output_file = '/tmp/glog.txt'
myoutput = open(path_to_output_file, 'w+')
process = subprocess.Popen(bash_command.split(), stdout=myoutput, stderr=myoutput)
output, error = process.communicate()
I get no Python errors, but it is like it hangs before it runs the subprocess.Popen. I have some logging that shows all is fine before that call, but then nothing happens, it just seems to hang.
If I restart the process, all works fine
I am wondering how I can find out more information on what is happening, or perhaps set a timer or something to check that it is running and if not do something
Thanks

How to force quit my python-made exe

I've got a little python app that I used pyInstaller on to create an exe file:
import subprocess
try:
taskCommand = 'tasklist /FI "ImageName eq pc-client.exe"'
reply = subprocess.Popen(taskCommand, stdout = subprocess.PIPE).communicate()[0]
for line in reply.split("\n"):
if line.startswith("pc-client.exe"):
PID = line.split()[1]
print PID
except:
pass
try:
killCommand = ("TASKKILL /f /t /PID " + PID)
subprocess.Popen(killCommand, stdout = subprocess.PIPE).communicate()[0]
except:
pass
try:
print "Restarting Papercut Client..."
subprocess.Popen(r"\\server\path\to\file\filename.exe", stdout = subprocess.PIPE).communicate()[0]
except:
pass
sys.exit()
When the exe is run, it opens up in the windows command window, will run its code (it's non-interactive) and then I want the window to dissappear when its finished!
What should I put at the end of my python code to make the window close when completed. I've tried os.quit(), os._exit(), sys.quit() & sys.exit() but none of them actually close the window!
As I'm creating an exe from my code, should I use something else? I can't compile with the noconsole flag, as it needs it to actually run the commands...
Thanks.
You can block the windows command prompt from coming up at all by putting
console=False
in your spec file. For example:
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='YourApp',
console=False,
icon='IMGFolder\game_icon_cs6_icon.ico')
If you are running from the command line without a spec file, use the noconsole flag:
pyinstaller.py --noconsole yourscript.py
for more info on the PyInstaller options: https://pyinstaller.readthedocs.io/en/stable/usage.html#options
If you want the prompt to come up then close, sys.exit() works for me, but without seeing more code it will be hard to tell.
UPDATE
Since subprocesses are involved, keep in mind that the command prompt will remain open until all processes are resolved (parent and child).
It looks like you are killing the first task with its PID (I would print out the PID before you kill it to confirm you have the right one). Then you run the second task (the main file you want run?) but never kill it.
Are you trying to close the command prompt but keep the .exe running?
There is some good information about killing processes here:
How to kill a python child process created with subprocess.check_output() when the parent dies?

Python selenium CTRL+C closes chromedriver

How can I catch CTRL+C (a KeyboardInterrupt) without causing the chromedriver to close.
It closes the chromedriver when I run my script.py through cmd.
driver = webdriver.Chrome()
try:
while True:
#do stuff with chromedriver
except KeyboardInterrupt:
print "User pressed CTRL + C"
#do other stuff with chromedriver
It does catch the KeyboardInterrupt in my script, thus my script continues but the chromedriver also gets it and close itself.
EDIT 1:
The solution here doesn't work when you run the script through CMD or when you freeze the script with Pyinstaller and run it (IOError: [Errno 4] Interrupted function call)
EDIT 2:
I also tried by making the script ignore the Errno 4 (using try and except Exception) but still has the same result (chromedriver closes) so in short, this solution does not help at all.
Consider using the webdriver.Remote flavor. This option does not spawn a local version of the webdriver inside the interpreter, which should free you from the SIGINT hassle.
Initiate the webdriver in another shell - (chromedriver for Chrome, geckodriver for Firefox, etc.)
Take note of the listening port. I will use the defaults here: 9515 for chromedriver and 4444 for geckodriver.
In your python script:
Chrome:
driver=webdriver.Remote("http://127.0.0.1:9515",desired_capabilities=webdriver.DesiredCapabilities.CHROME)
Firerox:
driver=webdriver.Remote("http://127.0.0.1:4444",desired_capabilities=webdriver.DesiredCapabilities.FIREFOX)
I just tried #Krmit 's answer, with Selenium 4.8.2, python 3.11, and Geckodriver and it worked fine for what I wanted (to be able to cancel a sleep).
options=Options()
# options.profile = FirefoxProfile()
ps = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, signal.SIG_IGN)
driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)
signal.signal(signal.SIGINT, ps)
You can also just disable SIGINT handling while starting the driver. Like so:
import signal
...
ps = signal.getsignal(signal.SIGINT) # backup signal handler
signal.signal(signal.SIGINT, signal.SIG_IGN) # ignore signal temporarily
... = webdriver.Chrome(...)
signal.signal(signal.SIGINT, ps) # restore original handler

How can I prevent infinite loop in subprocess of python?

I am writing a python script that executes another program with bash command.
I am using subprocess.Popen() function for it. However in some conditions the external program gives me an error and tries to run same comment infinitely.
How can I catch that error and break Popen function.
Assume that program gives its error as an output.
You can use poll() or communicate() function for this. These methods return returncode once the process terminates. The return code is None as long as programme is running.
You can try using below code
from subprocess import Popen
process = Popen('bash your_script.sh')
while process.poll() is None:
print 'keep running'
process.terminate()

How to quit python script in gdb-python?

I am writing a python(v2.7) script in GDB(v7.5.1-0.7.29). I want to quit the python script when certain condition got false. But i do not want to quit GDB. I tried using sys.exit(), exit() and quit(), but in those case they also quit GDB. Is there any way to just quit the python script but not the gdb. Like ctrl + c command but i want this happend only when a certain condition got false.
CTRL+D does that
(gdb) pi
>>> [Press CTRL+D]
(gdb)
You have to raise an exception. Question is what exception to raise; whether you provide code to catch it and whether you want traceback to be printed or not.
If you don't mind traceback to be printed you can raise KeyboardInterrupt. But I presume you want graceful exit without traceback.
If you are writing code for class that integrates into GDB command then you can raise gdb.GdbError. It will be consumed by the code implementing command class and no traceback is printed.
If you are writing a script that is executed by sourcing it then you have to embed your whole script into try / except and catch exception you are raising. In fact, calling exit() also simply raises exception SystemExit, so you may write your script as:
try:
some code
if some_condition:
exit()
some more code
except SystemExit:
pass