Issues with repeatedly executing .pyc script - python

I am trying to make an script that will every second read string from a file, and execute it.
executer.pyc:
import os, time
f = open("/root/codename/execute","a")
f.write("")
f.close()
cmd=open('/root/codename/execute', 'r').read()
if not cmd=="":
os.system(cmd)
os.system("rm /root/codename/execute")
time.sleep(1)
os.system("python executer.pyc")
Problem is, that it constantly f's up whole ps -aux and other similiar commands.
How can i make, that it will kill itself and then launch itself again? My idea, is a parent script that will launch executer.pyc everytime that script closes itself. But how can i make it, that it will not have effect like executer.pyc? I know this whole system how it works is kinda bad, but i just need it this way (reading from file "execute"). Please help!
Thanks in advance!

instead of
os.system("python executer.pyc")
you can use execfile()

It will be much easier to let this script run continuously. Look at How to use a timer to run forever? This will show you how you can repeatedly execute the same command.

Related

How to run a script AND THEN save the output to a file?

I'm using Windows' Power Shell. I'd like to run a Python script that will take a long time to be finished (it's a code for data acquisition, so it'll take about a few hours to conclude). So, I'd like to be able to see all the prints and results on the terminal, but I would like to save all the output (in the end) as a string, a file or whatever.
I've been trying using the redirection commands like python example_file.py > output.txt , python example_file.py | tee output.txt and similars, but the problem is that those commands run all the script in the background and just show the results when it's finished (and, again, I'd like to be able to see the progress of the acquisition).
I've looked online and found that there's a command called "script" in Linux that serves for the same purpose that I want, but I've not found any equivalent for Windows Power Shell. I'm also accepting any solution in Python, it doesn't need to be necessarily on PS.
Please, someone help me?
EDIT: I'd like to see in real time the output. I mean, the intention is to see all the results of the code normally, as it's normally executed on the PS terminal, AND THEN save all the output to a file, to a string or whatever.
Example: if I run
from time import sleep
print('banana')
sleep(3)
print('banana again')
it'll show, on the terminal, the first 'banana' and then, after three seconds, it'll show 'banana again'. The problem is that with the above codes it'll execute the script on the background and then show the results at once. And that's not what I want.
I would use the following code:
from time import sleep
outputs = []
def myprint(print):
global outputs
print(print)
outputs.append(print)
myprint('banana')
sleep(3)
myprint('banana again')
open("output.txt", "w").write("\n".join(outputs))
The code now writes into(and creates if not already there) a file named output.txt all the things printed with the myprint() function. If you want, you can also access them if as single strings in the outputs array. Also, don't wonder, but in python you can use both " and ' as the same thing.

Python: Check if Program is being closed

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.

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

Run same script "infinite" times

I have a script that does random calculation and prints it, but now I need these results written in a text file. I edited it and now each time I execute this script, new results are appended in a text file. However, I need as many new results as I can get into the same text file, so is there a way to make it run again and again (and stop it when I want to by keyboard interrupt)?
I could do something like:
inf_loop=0
while inf_loop==0:
#code to append to text file
But the script is rather long, thus I need to have each line within the loop indented properly.
I cannot comment so I'm gonna say my opinion here.
tab is your friend here. If you're using Python IDLE, just select all the lines and hit Tab. If you wanna outdent, try shift + tab.
If indenting is a problem for you and you really want to hack this down, you could simply restart your script like this:
#!/usr/bin/env python
import os
# your script content
args=['some_name']
os.execlp('./your_script.py',*args)
Run the script from the directory it is located in. If you need to pass arguments, simply append them to args.
If your script finishes it will restart itself again and again...
If you're adamant that you don't want to change your existing script, create a new one, then keep calling the other...
while True:
execfile('/path/to/other/script.py')
Although you should really be putting the work of the other script into a function, then repeatedly calling that instead of the script...
while True:
call_your_function()

Closing console application after completion from Python

I have an exe file that I have to call with several parameters, and for this purpose I use a bat file. After I execute bat file command prompt does not close, but wait for me to press a key. Now I have to run this exe several times, and for this I want to run a script that will do it for me.
i = 0
for path in Paths
outout = codecs.open('runExe.bat', 'w')
output.write(PathToExe + " -param1" + " -param2 " + param2Val[0] + " -param3 " + param3Val[0] + " -param4 " + param4Val[0] + " -param5 param5Val")
output.close()
subprocess.call(["regsvr32.exe", path, "-u", "-s"])
subprocess.call(["regsvr32.exe", path, "-s"])
subprocess.call("runExe.bat")
i + = 1
where param3Val, param4Val, param5Val are lists with values for related command prompt parameters.
When I call this bat file, everything works perfectly for the first fun of exe, but after it executes, command promt waits for my respond. When I press any key, it closes and then exe file starts with different parameters.
So I want to eliminate with key-pressing thing. I tried to put "exit" to the end of the bat file, but it did not work. How can I close command prompt window from script, when exe finishes working?
Thanks in advance!
Upd1: sarmold's way of doing thing works fine, but I think this it is exe (console application) that is waiting for my response. Smth in exe file prevents console window from closing, but I do not have access to sources. How can I close it's window after it executes?
Upd2: I have tried to add "shell" call after subprocess.call, but this does not seem to work either, still have to respond to the console manually :(
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("Command Prompt")
shell.SendKeys("cls(ENTER)")
There are two possible approaches here:
Make only a single bat file that contains all your commands, including the regsvr32.exe commands, and execute that.
Have the Python script do everything for you.
For the first approach, use the "a" open mode to append to the batch file. (Perhaps delete it at script start.) Write the contents of your three commands to the batch file within the loop -- so you wind up with a long batch file that includes all the commands you need.
Then call the subprocess.call() command once, outside the loop, at the end of the script, to run the entire thing.
For the second approach, remove all the batch-file writing and run your PathToExe using Python's subprocess.call(). It's almost as simple as deleting all lines that work with output, but change output.write() to subprocess.call() -- and obviously, fiddle with the contents a little bit so they work for subprocess.call() directly.
Are you running this in a way that launches a command prompt every time you run runExe.bat? It shouldn't necessarily wait for you to close the console, but since it does, try running your script with subprocess.call("cmd /C runExe.bat").
#Arnold is right, though: It's better to simplify your set-up and (imho) just let python handle everything.

Categories