How do I get main to run again without executing the whole script again?
import sys #importing module that is used to exit the script
def main ():
#doing stuff
main ()
#Re-run the script - looking for a cleaner way to do this!
def restart ():
restart = input("Press any key + Enter to start again, or x + Enter to exit.")
if(restart != "x"):
exec(open("./calc.py").read())
# not sure how to run main() again without calling out the script name again?
else:
print ("Exiting!")
sys.exit ((main))
restart ()
#End of Program
You can re-run the main module-method as many times as you want by directly calling main() sequentially:
def main( ):
# Code goes here...
return;
main();
main();
main();
However, if you want the user-interaction like your restart method has, you might want to consider defining main with an optional parameter (one that has a default value) that controls whether you ask to re-run the method or not.
def main( argv, AskRestart= True ):
# Main code goes here....
if ( AskRestart ):
# User interaction code goes here ...
return;
Also, you can look into the atexit package in Python 3.5.1 to see how you can assign a method to be run only when exiting the interpreter:
https://docs.python.org/3.5/library/atexit.html
That would allow you to do whatever you want and then when everything is done, give someone the option of restarting the entire module. This would remove the reliance on the exec call, and be a more coherent and simpler approach to getting the exact same expected functionality.
In addition to Tommy's great advice, (I'm not sure of your goal in continually restarting main() as main is an empty function that doesn't do anything yet, but..) one way to have main continually repeat until the user enters x may be to use a while True loop:
import sys #importing module that is used to exit the script
def main ():
#doing stuff
restart() # <-- use main to restart()
#Re-run the script - looking for a cleaner way to do this!
def restart ():
restart = raw_input("Press any key + Enter to start again, or x + Enter to exit.")
while True: # <-- key to continually restart main() function
if(restart != "x"):
exec(open("./calc.py").read())
# not sure how to run main() again without calling out the script name again?
main() # <-- restart main
else:
print ("Exiting!")
sys.exit ((main))
restart ()
#End of Program
Hope this also helps!
Related
I wrote a app that restarts explorer.exe but the problem is that after i re-open explorer.exe it should call the main function again, but it doesn't.
The 'funny' stuff that i found is that if i dont open explorer.exe, the main function will be called as it should.
import os
def sendCmd(command):
return os.system(command)
# Main function
def Main():
sendCmd('cls')
q = input() # Checks for input
if q == "1": # If the option 1 is selected
sendCmd("taskkill /f /im explorer.exe") # Kills explorer
sendCmd("explorer.exe") # Opens explorer
Main()
Thanks!
nice question, my guess is that python uses the main thread when explorer.exe is open so it is not going forward to the Main() function and does not do that command. try to close explorer.exe manually and check if the program calls the main function.
Anyway, To solve that you can call the sendCmd("explorer.exe") in another thread and your program will continue to the Main() line (I would use while True in this case instead of recursion https://www.geeksforgeeks.org/difference-between-recursion-and-iteration/)
th = threading.Thread(target=sendCmd, args=('explorer.exe', ))
# Start the thread
th.start()
I have a python script that goes like this -
import..
def main ():
some_condition check
main() #calling main again
some condition check
main() #calling main again
main()
The idea here is to let the script run indefinitely and check for something.
This way of calling main() somehow seems incorrect.
I am quite new to Python scripting. Can someone guide me if this very inefficient and if yes then how do I achieve this?
What you are doing is called recursion. This is certainly not good for long running applications, since it would cause a stack overflow.
Do your checking like this:
quit = False
while not quit:
do_your_check()
#maybe sleep
quit = should_i_stop()
Just put the things you want to do in a while true loop.
import ...
def main():
while True:
some_condition check
Recursion is utilized when it is too complex/hard to write as iterative code. e.g. Tree traversals.
I'm doing python coding with Emacs.
I find it troublesome to get Emacs inferior shell exited whenever I call sys.exit. How can the code break from __main__ block without killing Emacs inferior shell process, without introducing another indented block?
if __name__ == "__main__":
# doing something
if args.init:
init_env(cfg_dict, args)
exit(0) # <--- this kills the Emacs sub-shell
# otherwise doing something
# ...
P.S. I slept on the title of this question for a while, but I couldn't think of better title. :-(
Why not wrap the main code in a function and make use of return:
def main():
# doing something
if args.init:
init_env(cfg_dict, args)
return
if __name__ == "__main__":
main()
I need to say first and foremost, I am just learning Python.
I am making a simple python program that has a menu option for exiting the program by using a function I called exit. I have tried making the exit function just call break, but I am getting an error when the exit function is called.
Any help would be greatly appreciated.
Sorry for not posting code earlier....
def exit():
break
evade = evade_fw()
# Main program running dialogue
def main(): # menu goes here
opt_list = [xsl_file,
basic_loud_scan,
fw_main,
exit
]
Just forget about your own exit() function. You can simply do:
from sys import exit
And the exit() function from sys module will do the job.
It's also worth to know what happens under the hood. Function sys.exit() actually throws a special exception. You can do it as well explicitly and without importing anything:
raise SystemExit()
break is for breaking out of for or while loops, but it must be called from within the loop. I'm guessing that you expect the break to break out of your program's main event loop from an event handler, and that is not going to work because, as aforementioned, the break must be within the loop itself.
Instead your exit function can clean up any resources, e.g. open files, database connections, etc. then call [sys.exit()][1] which will cause the Python interpreter to terminate. You can optionally pass a status code to sys.exit() which will be the system exit status available to shell scripts and batch files.
import sys
def exit():
# clean up resources
sys.exit() # defaults to status 0 == success
I have two programs
program1.py is like commandline interface which takes command from user
program2.py has the program which runs the relevant program as per the command.
Program 1 has also has an quit_program() module
In our simple universe.. lets say I have just one command and just one program
So lets say...
program1.py
def main():
while True:
try:
command = raw_input('> ')
if command == "quit" :
return
if command == '':
continue
except KeyboardInterrupt:
exit()
parseCommand(command)
And then I have:
if commmand == "hi":
say_hi()
Now program2 has
def say_hi():
#do something..
Now there can be two cases...
Either say_hi() completes in which case no issue...
But what i want is that if user enters a command (say: end)
then this say_hi() is terminated in between..
But my current implementation is very sequential.. I mean I dont get to type anything on my terminal untill the execution is completed..
Somethng tells me that the say_hi() should be running on another thread?
I am not able to think straight about this.
Any suggestions?
Thanks
The threading module is what you are looking for.
import threading
t = threading.Thread(target=target_function,name=name,args=(args))
t.daemon = True
t.start()
The .daemon option makes it so you don't have to explicitly kill threads when your app exits... Threads can be quite nasty otherwise
Specific to this question and the question in the comments, the say_hi function can be called in another thread as such:
import threading
if commmand == "hi":
t = threading.Thread(target=say_hi, name='Saying hi') #< Note that I did not actually call the function, but instead sent it as a parameter
t.daemon = True
t.start() #< This actually starts the thread execution in the background
As a side note, you must make sure you are using thread safe functions inside of threads. In the example of saying hi, you would want to use the logging module instead of print()
import logging
logging.info('I am saying hi in a thread-safe manner')
You can read more in the Python Docs.