How to run the Python program forever?

+1 vote

I need to run my Python program forever in an infinite loop..

Currently I am running it like this -

#!/usr/bin/python 

import time 

# some python code that I want 

# to keep on running 

# Is this the right way to run the python program forever? 

# And do I even need this time.sleep call? 

while True:

time.sleep(5)

Is there any better way of doing it? Or do I even need time.sleep call? Any thoughts?

Jul 27, 2018 in Python by bug_seeker
• 15,350 points
763 views

3 answers to this question.

+1 vote

Yes, you can use a while True: loop that never breaks to run Python code continually.

However, you will need to put the code you want to run continually inside the loop:

#!/usr/bin/python 

while True:

# some python code that I want  

# to keep on running

Also, time.sleep is used to suspend the operation of a script for a period of time. So, since you want yours to run continually, I don't see why you would use it.

answered Jul 27, 2018 by Priyaj
• 56,920 points
+1 vote
No, you can use while: pass

I used it recently in my project.
answered May 20 by Lehan
Works like a charm!
+1 vote
you can also do the old fashioned method of while(1==1)

{

#code you want to run

}
answered Jun 10 by brianno
Hahaha! This is the old fashioned way, we learnt in school days. But works like a charm.

Firstly, python don't support curly braces. Secondly, isn't while(1==1) same as using while Trueas (1==1) will return boolean value True only.

Related Questions In Python

0 votes
1 answer

how to check the syntax of python program without running the program?

Yes, it is possible to check the ...READ MORE

answered Jun 27 in Python by Arvind
• 2,960 points
44 views
0 votes
2 answers

how to print the current time using python?

print(datetime.datetime.today()) READ MORE

answered Feb 14 in Python by Shashank
• 1,350 points
58 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,340 points
110 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 346 views
+4 votes
6 answers
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8 in Python by rajesh
• 1,210 points
81 views
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29 in Python by rajesh
• 1,210 points
105 views