问题
I am currently trying to run a .py
file but in a loop.
Just for a test I am using
I = 0
while I<10:
os.pause(10)
open(home/Tyler/desktop/test.py)
I = I + 1
I am sure this is a very simple question but I can't figure this one out. I would also like to add in the very end of this I have to make this run infinitely and let it run for some other things.
回答1:
There are a few reasons why your code isn't working:
- Incorrect indentation (this may just be how you copied it on to StackOverflow though).
- Using
os
without importing it. - Not using quotes for a string.
- Mis-using the
open
function;open
opens a file for reading and/or writing. To execute a file you probably want to use theos.system
.
Here's a version that should work:
import os
i = 0
while i < 10:
os.pause(10)
os.system("home/Tyler/desktop/test.py")
i += 1
回答2:
Python is indentation-sensitive, and your code is missing indentation after the
while
statement!Running the
open
command will not run the Python script. You can read what it does here in the docs: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-filesThis stack overflow question talks about how to run Python that's stored in another file How can I make one python file run another?
I recommend wrapping the code you want to run in a function, e.g.
def foo(): print 'hello'
and then saving this in foo.py. From your main script, you can then do:
import foo i = 0 while i < 10: foo.foo() i += 1
If you want to run something in an infinite loop, you need the condition for the
while
loop to always be true:while True: # do thing forever
A note on importing: The example I have given will work if the foo.py file is in the same directory as the main Python file. If it is not, then you should have a read here about how to create Python modules http://www.tutorialspoint.com/python/python_modules.htm
来源:https://stackoverflow.com/questions/35998544/running-a-py-file-in-a-loop