Python: Check if Program is being closed - python

all.
Is there a way, using Python, to check if the script that is currently running is requested to close? For example, If I press the X-Button (close program button) on the top-right to close it, or end the script in any other way, can the script do some code before it ends? Example:
# script goes here...
if Script_To_Be_Closed: # replace this with an actual line of code.
do_stuff

There are multiple options you may use, like trapping keyboardinterrupts, but the simplest is atexit, which executes a function whenever a scripts is ended (except of a hard process kill indeed).
import atexit
def my_exit_function(some_argument):
// Your exit code goes here
print(some_argument)
if __name__ == '__main__':
atexit.register(my_exit_function, 'some argument', )
// Your script goes here

You can use a shell script to do the job
You can see the script command shown below which calls itself after executing the command to run the python file. once the python file is closed the next line will force the python command to run again. you can also customise the behaviour the way you want.
main.py
#!/bin/bash
python3 ./main.py
source ./infiniteRun.sh
If you need to stop the job just edit the file and remove the last line source ./infiniteRun.sh and save the file.

Related

How to end a python subprocess with no return?

I'm working on a BCP wrapper method in Python, but have run into an issue invoking the command with subprocess.
As far as I can tell, the BCP command doesn't return any value or indication that it has completed outside of what it prints to the terminal window, which causes subprocess.call or subprocess.run to hang while they wait for a return.
subprocess.Popen allows a manual .terminate() method, but I'm having issues getting the table to write afterwards.
The bcp command works from the command line with no issues, it loads data from a source csv according to a .fmt file and writes an error log file. My script is able to dismount the file from log path, so I would consider the command itself irrelevant and the question to be around the behavior of the subprocess module.
This is what I'm trying at the moment:
process = subprocess.Popen(bcp_command)
try:
path = Path(log_path)
sleep_counter = 0
while path.is_file() == False and sleep_counter < 16:
sleep(1)
sleep_counter +=1
finally:
process.terminate()
self.datacommand = datacommand
My idea was to check that the error log file has been written by the bcp command as a way to tell that the process had finished, however while my script no longer freezes with this, and the files are apparently being successfully written and dismounted later on in the script. The script terminates in less than the 15 seconds that the sleep loop would use to end it as well.
When the process froze my Spyder shell (and Idle, so it's not the IDE), I could force terminate it by closing the console itself and it would write to the server at least.
However it seems like by using the .terminate() the command isn't actually writing anything to the server.
I checked if a dumb 15 second time-out (it takes about 2 seconds to do the BCP with this data) would work as well, in case it was writing an error log before the load finished.
Still resulted in an empty table on SQL server.
How can I get subprocess to execute a command without hanging?
Well, it seems to be a more general issue about calling helper functions with Popen
as seen here:
https://github.com/dropbox/pyannotate/issues/67
I was able to fix the hanging issue by changing it to:
subprocess.Popen(bcp_command, close_fds = True)

Python script does not execute correctly when calling another program with os.system('./myProgram')

I have a python script calling another program with the os.system command. It is a very complex program which can be called in the Terminal using ./myProgram. I want to automatically execute said program and do different stuff (which works fine) in between.
Somehow this works:
print('start')
os.system('ll')
print('end')
But calling the program with the python script:
print('start')
os.system('./myProgram')
print('end')
just executes myProgram without showing the print statements. myProgram itself displays information in the terminal.
Later I want to do more than just print something in between.
I tried using the subprocess module:
print('start')
subprocess.call('./myProgram', shell = True)
print('end')
which shows the same results as the os.system module.
Which properties of a program do not allow my python script to run properly?
And how can I call another program with my python script, execute said program and continue with the script afterwards?
u can always use a safe and secure way to call it
if u want to call app.py in the folder scripts_folder
just write:
from scripts_folder import app
Now if u have a def inside app.py for example my_def_example() u can call it by writing:
app.my_def_example()

How can I stop a python script on a batch file

I want to start a python script and then automatically close that script after 2 minutes, run another command, and keep doing the same thing again like this (loop) forever :
Cd c:/location.of.script/
pythonscript.py
Stop (like ctrl+c) pythonscript.py after 120s
Del -f cookies.file
.
.
.
Is this even possible with a batch file on windows 10? If so, can someone please help me with this?
I’ve been looking everywhere but found nothing except the exit() command which stops the script from inside - this isn’t what I want to do.
You can change your python script to exit after 2 minutes, and you could batch file that has a while loop that runs forever and run the python script then deletes the cookie.file, I don't know if that's exactly what you want, but you can do it by putting a timer in your python script.
You can make a separate thread that keeps track of the time and terminates the code after some time.
An example of such a code could be:
import threading
def eternity(): # your method goes here
while True:
pass
t=threading.Thread(target=eternity) # create a thread running your function
t.start() # let it run using start (not run!)
t.join(3) # join it, with your timeout in seconds
And this code is copied from https://stackoverflow.com/a/30186772/4561068

How to execute another python file and then close the existing one?

I am working on a program that requires to call another python script and truncate the execution of the current file. I tried doing the same using the os.close() function. As follows:
def call_otherfile(self):
os.system("python file2.py") #Execute new script
os.close() #close Current Script
Using the above code I am able to open the second file but am unable to close the current one.I know I am silly mistake but unable to figure out what's it.
To do this you will need to spawn a subprocess directly. This can either be done with a more low-level fork and exec model, as is traditional in Unix, or with a higher-level API like subprocess.
import subprocess
import sys
def spawn_program_and_die(program, exit_code=0):
"""
Start an external program and exit the script
with the specified return code.
Takes the parameter program, which is a list
that corresponds to the argv of your command.
"""
# Start the external program
subprocess.Popen(program)
# We have started the program, and can suspend this interpreter
sys.exit(exit_code)
spawn_program_and_die(['python', 'path/to/my/script.py'])
# Or, as in OP's example
spawn_program_and_die(['python', 'file2.py'])
Also, just a note on your original code. os.close corresponds to the Unix syscall close, which tells the kernel that your program that you no longer need a file descriptor. It is not supposed to be used to exit the program.
If you don't want to define your own function, you could always just call subprocess.Popen directly like Popen(['python', 'file2.py'])
Use the subprocess module which is the suggested way to do that kind of stuff (execute new script, process), in particular look at Popen for starting a new process and to terminate the current program you can use sys.exit().
Its very simple use os.startfile and after that use exit() or sys.exit() it will work 100%
#file 1 os.startfile("file2.py") exit()

Run an executable, wait for it to produce output, run another program

Within a Python script, I'm trying to execute the following sequence of events:
Open a command window and run a program. When it completes, it outputs a text file.
Once that text file has been created, close the program.
After that has happened, run a new program using the text file as an input
Here's what I have so far:
subprocess.popen(['cmd','/c',r'programThatRuns.exe'])
subprocess.wait() # ? subprocess.check_call()? kill?
subprocess.popen(['cmd','/c',r'otherProgramThatRuns.exe'])
So I guess I'm really stuck on the second line
I think all you need is:
subprocess.check_call(['programThatRuns.exe'])
subprocess.check_call(['otherProgramThatRuns.exe'])
The check_call function will run the program and wait for it to finish. If it fails (non-0 exit code) it will throw a CalledProcessError exception.
You generally don't want to run programs through cmd, just run them directly. You only need to force using cmd if the program isn't an executable, e.g. for a builtin command like dir, for a .bat or .cmd file, or if you want to use file associations.
Have you tried using subprocess.call?
Python 2 - Python 3
Run the command described by args. Wait for command to complete, then return the returncode attribute.
Seems to be what you're trying to do. Simply run the first process, check that the file exists, and pass the file into the second process to use.
subprocess.check_call will also work for what you're trying to do, except that if the process returns a non-zero return code it'll raise an exception while call will simply return the return code.
You have to apply 'wait' on the child process, i.e.
o = subprocess.popen(['cmd','/c',r'programThatRuns.exe'])
o.wait()
subprocess.popen(['cmd','/c',r'otherProgramThatRuns.exe'])
or you use check_call

Categories