I'm working on a python program that should wait for another program to update a .txt file, and when the file was updated my program should open it, get the command the other program just made, and then run something else. I'm quite new to python so a generic but well-explained solution would be great.
I've found How do I watch a file for changes? that leads to the solution here, but I can't quite understand how this works. The program could also be in other languages but it should trigger my python modules.
Here's the general idea of what I'm looking for.
sub GET_FILE_UPDATE:
try:
while change == False:
time.sleep(1)
else
if change == True
'open file and read command'
run.command()
except KeyboardInterrupt:
'stop program'
Related
I have tried doing;
os.system('python currentfile.py')
sys.exit() or quit()
but instead of closing, the current python file just becomes unresponsive causing an undesired 'not responding' loop. The first file is a sign-in module which is supposed to open another py file and then close itself but it doesn't seem to work at all. I've also tried the subprocess.Popen method and the result is still not what I want.
I have two python scripts, one that needs to continuously get input from the user and write into a file while the other simultaneously continuously check for updates from the file. My problem is that when running the check script, the os system terminal "position" seems to be already filled and I can not run the input script. It either shows the check scripts terminal or stays on a blinking cursor on the cmd terminal and not loading up. Also, I am unable to find a way to make both of the scripts run indefinitely until the user kills the process. Also, it might be my pc, but when running
while True:
check()
in my check script, it freezes my pc and also does not allow the input script to run
BTW, my pc had been having some problems, so I am going to reset it today and I hope that is the problem, but I have been going crazy over this problem and don't trust my judgement on this anymore:(
#my check script
def check():
with open('Tasks.txt','r') as file:
data = file.readlines()
if not "Neuron" in data and len(data)!=0:
i=0
Chars = data[0].split(" ")
while(i<len(Chars)):
c=0
print(len(data[0]))
print('Count:' + str(i))
print('Chars are ' + Chars[i])
while(c<len(Chars[i])):
Neuron.createNeuron(Chars[i][c-1:c])
c+=1
i+=1
data.pop(0)
Neuron.writeData('Tasks.txt',data,'w')
#os.system('py Create.py')
check()
#my user input script
def CM():
String = input(">")
#res = ' '.join(format(ord(x), 'b') for x in String)
#print(res)
Neuron.writeData('Logs.txt',Neuron.writeData('Tasks.txt',(' '.join(format(ord(x), 'b') for x in String)+'\n'),'a'),'a')
CM()
CM()
So, I found the answer. Originally both files actually could run, but one of them, the input file, had to be opened from the IDLE and then run there. To run them both simultaneously repetitively was to put
os.system('py Create.py')
at the end of the file. So it would run a new session of the py script.
Also, I imported a file that was not just functions but commands also and it ran them, which is why I was unable to use the Input script.
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()
This question may have been asked a couple of times but I cannot seem to find it.
Basically I am just learning Python and I am on Windows, this means I double click the .py file and open it. This works great until an error appears, at which point Python calls exit and the window closes.
One way, of course, to get around this is to use the cmd program in Windows and run the Python program from there, however, is there a way to fix it so that my application doesn't bail out and close as soon as it hits an error if I open it from Windows Explorer?
while(True):
try:
number = input('Enter a number: ')
if(is_int(number) is False):
print('Please actually enter a number')
if(number > 0):
answer = input('Oh Noes you really want that?')
if(answer == 'yes'):
sys.exit(0);
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
input('')
In order to keep your program intact, e.g. to not introduce unwanted catch-em-all exception handling (aka pokemon handling) there are at least three options:
Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
Use text editor plugins for running python code. At least notepad++ and sublime text are capable of doing so.
I would recommend starting with option 1 for starters, then slowly move to option 3 for small scripts and projects, and option two for larger ones.
I you put an input function at the bottom of your script then it will hang there until you hit enter or close the command prompt. If you call an exit function put it immediately before the exit function is called. Otherwise place it at the bottom of the script.
Also I assume you have defined is_int already in your script?
What would you think it should do?
Python is drawing the window you see, if python crashes, the windows is going away.
You can run it trough cmd, or within an IDE. (like IDLE, that has some problem though when it comes to GUI)
Otherwise, add something like this at the end of the file
try:
run()
except Exception as inst:
print type(inst), inst.args
#it prints the exception
print sys.exc_traceback.tb_lineno
#if you want the line number where the error occurred in the source code
raw_input()
inst is the exception instance, you can see the type and the list of arguments.
Then with the sys module you can also see the line where the error occurred in the code.
This way every error will be handled and displayed before closing
Is this the right way?
No. You should really be using ad IDE (like Eclipse with PyDev or PyCharm).
After #SeçkinSavaşçı's extremely useful comment at the start:
The most common way is to let it wait for an input, then ignore the input and terminate the script.
Which took me a second to understand I went in search of how to do this, so first I saw to stop the script and used:
while(True):
try:
# Application code here
except:
input('')
Which worked really well to catch all errors, which unlike in PHP (which I have become comfortable with unfortunately) are all exceptions.
So the next part was to to tell me what error had occured and how to fix it, I needed a backtrace. It just so happens that the Python docs gave me the answer right here: http://docs.python.org/2/library/traceback.html#traceback-examples in an easy to see example:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout));
Add that above the input('') and I had my perfect error handling showing me everything I needed.
Thanks all,
Try import time and time.sleep(). Also, I recommend you to use IDLE or Geany. I've been using them and they work out well.
I have downloaded and compiled jsmin.c, and run it on a javascript file from the terminal, and it seems to work great. But when I call it from an os.system() or os.popen() call in a python script (on the same input file), the output file (the minified version of the js file) gets truncated, as though stdout were not getting flushed before the subprocess exits, or as if jsmin were terminating early, or as if maybe something were going on with disk buffering or something.
But none of those things seem to be the case. The exit value is whatever I return from main() even when the output is getting truncated, and adding a call to fflush(stdout) doesn't make any difference, and calling sync from within the same subshell after calling jsmin doesn't make any difference.
I tried replacing calls to putc() with calls to fputc(), and at first it seemed like that fixed the problem (for some unfathomable reason?), but then, inexplicably, the problem started happening again, and now happens reliably. Bizare?
I would say it's some problem with jsmin.c, but the program works fine on the same input file when run from the command line, so it has something to do with running it from a python subprocess.
Here's my subprocess call:
result = os.system('jsmin < ' + tpathname + ' > ' + tpathname + '.min')
(I have put jsmin in the path, and it is running, I get most of the expected results in the .min file.)
Can anyone imagine what might be causing this problem?
Stack Overflow wouldn't let me answer my own question for 5 hours or something like that, so this 'answer' was originally added as an edit. (It also wouldn't let me chat, so the comments stretched on for a bit.)
I found the problem. The problem was with the python program that was creating the input file for jsmin and then calling jsmin on it. It was creating a file, failing to close it (yet), and then calling jsmin on it. So jsmin was not terminating early, nor was it having it's output truncated; rather, it was operating on an (as yet) incomplete input file. (Duh.)
I would have realized this a lot earlier than I did, except that the python program was eventually closing jsmin's input file (by exiting), so by the time I was examining it, it appeared complete. It's just that it was not complete by the time jsmin was processing it.
This very thing is one of the motivations for the 'with' idiom:
with open(targetpath, 'w+') as targetfile:
..code that writes to targetfile