?
Solved

OS command

Posted on 2011-10-05
10
Medium Priority
?
337 Views
Last Modified: 2012-05-12
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 ?
0
Comment
Question by:dolamitejenkins
  • 6
  • 4
10 Comments
 
LVL 17

Expert Comment

by:gelonida
ID: 36921486
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.


0
 
LVL 17

Expert Comment

by:gelonida
ID: 36921580
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

0
 
LVL 17

Expert Comment

by:gelonida
ID: 36921621
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,
0
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

 

Author Comment

by:dolamitejenkins
ID: 36921663
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...
0
 
LVL 17

Expert Comment

by:gelonida
ID: 36923555
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

0
 

Author Comment

by:dolamitejenkins
ID: 36926829
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

0
 
LVL 17

Accepted Solution

by:
gelonida earned 2000 total points
ID: 36927592
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

0
 

Author Comment

by:dolamitejenkins
ID: 36928415
thanks I'm trying this code now ... it may be awhile before we know if it works because I have to reproduce the error
0
 

Author Closing Comment

by:dolamitejenkins
ID: 36935024
only way I could resolve it was to us os.exit(0) when the error occures
0
 
LVL 17

Expert Comment

by:gelonida
ID: 36936290
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?

0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question