OS command

is there a way to or is there an OS command that I can use to close my program and then restart it or force the program to restart ? IKNOW ABOUT SYS.EXIT BUT HOW DO i RESTART ?
dolamitejenkinsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gelonidaCommented:
the closest you can get would be
os.exec()

it allows you to start create a new process, which will replace (and thus terminate) your current
process

passing it sys.argv should do the job.

I'll try a small example and will post it.


gelonidaCommented:
Attached code is tested under Linux.
However I never tried this with a huge python scripts, which might have open files / sockets / etc.

It will not work under windows.


Just run the program and enter random text end confirm with enter.

You see, that the variable counter increments.

if you enter the text restart, then your program will be restarted.

you can verify with top or ps, that no new process shows up, but you will see, that your counter variable is reset.


#!/usr/bin/env python
import os
import sys

print "SYS.argv = %r" % sys.argv

counter = 0
while True:
    line = raw_input()
    print counter, "<%s>" % line.strip()
    counter += 1
    if line == 'restart':
        args = [ sys.executable ] + sys.argv
        print "will restart %r %r" % (sys.executable, args)
        os.execv(sys.executable, args)

Open in new window

gelonidaCommented:
If you give some more context of why you want to restart, then there might be other solutions.


A simple one could be for example two python scripts.

the first one  would just be a loop
starting the second python script with
subprocess.popen


the second python script could abort whenever it likes to.
It would always be restarted again by the first python script.

If you want to have a condition, where you do not want to restart you could for example use the exit code of sys.exit()
if the exit code is 0, then the first script would abort
if it were not 0 the first script would relaunch the second one.

If this option might be intersting, then I can send you some sample code,
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

dolamitejenkinsAuthor Commented:
it's the problem you helped me solve the other day ... window OS coming out of sleep/ hibernate some times causes and error... your solution is right on  the money "kernel32.SetThreadExecutionState(ctypes.c_int(ES_SYSTEM_REQUIRED|ES_CONTINUOUS|ES_DISPLAY_REQUIRED))" ... but I want to put an exception in anyway just in case and the only way to clear this particular error is to close the program and restart.... so I was going to wx.messagedialog " sorry the program has encountered and error and must exit... i was thinking if I could also have it restart that would make people happier.... instead of a simple sys.exit and they have to restart...
gelonidaCommented:
perhaps in your case attached code snippet might be enough.


Whenever your application would raise an exception it would just restart the main function.

HOWEVER:

- This will not work if the exception was not raised in the main thread
- YourSpecificException is a place holder for the exception, that should
   trigger a restart.


If The exception is in another thread, then an approach of having one small Python script just launching your application, verifying the exit code and relaunching it in case of a special exit code could be an option.
def main():
    your_code()
    sys.exit(0)

def restart_main():
    while True:
        try:
            main()
        except YourSpecificException as exc: 
            pass


if __name__ == "__main__":
    restart_main()

Open in new window

dolamitejenkinsAuthor Commented:
Ok so here is a chopped down code snippet ... It runs perfectly 99 times out of 100 ... there has been a glitch in on line of my code ..
  Pulse = str(self.pulse.GetStringSelection())

Open in new window


It's some kind of glitch because when it happens I get "AttributeError" str ' object has no attribute 'GetStringSelection' when obviously it does... never get that error anywhere else just there and not all the time so I cant find what causes it(except demoing the code for people..lol) so I thinking about handling the error by direction it to start over or is there a way to tell the code to  complete the task just forget that one value ?





 
 self.diastolic = wx.Choice(panel, -1, pos=(485,320),size=(45,-1), choices =bp,name="")        
	self.respiration  = wx.Choice(panel, -1, pos=(580,320),size=(45,-1), choices =bp,name="")        
	self.pulse = wx.Choice(panel, -1, pos=(680,320),size=(45,-1), choices =bp,name="")     

def OnInsert(self, event):
        con = lite.connect('specialeventms2.sqlite')
        cur = con.cursor()
        Provider_2= str(self.tc21.GetStringSelection())
        Sys = str(self.systolic.GetStringSelection())
        Dia = str(self.diastolic.GetStringSelection())
        Pulse = str(self.pulse.GetStringSelection())
cur.execute('insert into ptrecords values(?,?,?,?,0)',
                    (,Sys,Dia,Pulse,l))
        con.commit()
        cur.close()
        con.close()

Open in new window

gelonidaCommented:
The solution depends on the exact nature of this Attrinute error:

!. Perhaps looping helps (probbaly not)
You could just  retry. I don't believe it will work tthough


2.) Perhaps retrying a few seconds later might work
In this case just detect the excation. start a timer (doin't use sleep !!!!),
which will trigger OnInsert  a few seconds later


3.) If 2.) doesn't work, then you set a global variable indicating, that you want to restart
            and quit the WxWidgets main loop (and restart it from main)
def OnInsertWithLoop(self, event):
        all_ok = True
        retry_count = 5
        while all_ok is False) and retry_count > 0:
            con = lite.connect('specialeventms2.sqlite')
            cur = con.cursor()
            Provider_2= str(self.tc21.GetStringSelection())
            Sys = str(self.systolic.GetStringSelection())
            Dia = str(self.diastolic.GetStringSelection())
            try:
                Pulse = str(self.pulse.GetStringSelection())
            except AttributeError:
                retry_count -= 1
                continue
        if not all_ok:
             # nothing I can do.
             # either I save a bad pulse value 
             Pulse = 0 # (hopeflly not ;-) 
             # or I just abort
             return # uncomment if you want to save an invalid pulse entry
        cur.execute('insert into ptrecords values(?,?,?,?,0)',
                    (,Sys,Dia,Pulse,l))
        con.commit()
        cur.close()
        con.close()


def OnInsertWithRetrigger(self, event):
        con = lite.connect('specialeventms2.sqlite')
        cur = con.cursor()
        Provider_2= str(self.tc21.GetStringSelection())
        Sys = str(self.systolic.GetStringSelection())
        Dia = str(self.diastolic.GetStringSelection())
        try:
            Pulse = str(self.pulse.GetStringSelection())
        except AttributeError:
            # WxWisdgets command to start a timer calling OnInsert
            # in X seconds
            return
cur.execute('insert into ptrecords values(?,?,?,?,0)',
                    (,Sys,Dia,Pulse,l))
        con.commit()
        cur.close()
        con.close()

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dolamitejenkinsAuthor Commented:
thanks I'm trying this code now ... it may be awhile before we know if it works because I have to reproduce the error
dolamitejenkinsAuthor Commented:
only way I could resolve it was to us os.exit(0) when the error occures
gelonidaCommented:
So what is your final solution?

Do you have now 2 python scripts?
your application script and another one just restarting it dependiong on its exit code?

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.