Running a .py file in a loop

守給你的承諾、 提交于 2021-02-16 15:38:14

问题


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:

  1. Incorrect indentation (this may just be how you copied it on to StackOverflow though).
  2. Using os without importing it.
  3. Not using quotes for a string.
  4. Mis-using the open function; open opens a file for reading and/or writing. To execute a file you probably want to use the os.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-files

  • This 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!