Hey I'm working on a python project that requires an action that takes a couple minutes. The thing is since it takes a couple minutes I'd like the user to be able to press enter to see the current status of the action. How can I do this in Python 2?
Asked
Active
Viewed 218 times
1
-
Is this a command line project or one with UI? Can you post some code of how you launch the background task? – pajton Mar 26 '11 at 21:59
-
It's a command line project. And it's a simple port scanner. I just want it to write which port it's scanning when the user presses enter. – Jmariz Mar 26 '11 at 22:01
-
The simplest way would be to use threads I guess. One thread scanning ports and the other waiting for user input. – pajton Mar 26 '11 at 22:04
-
1Why don't you just display a [progress bar](http://stackoverflow.com/questions/3160699/)? – Björn Pollex Mar 26 '11 at 22:04
-
A progress bar is a good idea but I use a for loop so I have a lot of problems with it. – Jmariz Mar 26 '11 at 22:24
1 Answers
0
@Space_C0wb0y is right, a progress bar is a good solution. However, this demonstrates one way to do what you asked for. Some code pinched from here: Non-blocking read on a subprocess.PIPE in python
import fcntl, os, sys
# make stdin a non-blocking file
fd = sys.stdin.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
def enter_pressed():
data = sys.stdin.read(1)
return bool(data)
i = 0
while True:
i += 1
if enter_pressed():
print(i)