I am trying to write a script that reads from a text file and outputs the content using a type writer effect. I have been able to acheive this using the following code
import sys
from time import sleep
f=open("test.txt", "r")
words = f
for char in words:
sleep(0.5)
sys.stdout.write(char)
sys.stdout.flush()
Which works, however I would like to turn this into a loop so that the text prints, the screen (output) is cleared, a one second pause and then the text prints again (with same keyboard effect).
I have tried this
import sys
from time import sleep
f=open("test.txt", "r")
while True:
words = f
for char in words:
sleep(0.5)
sys.stdout.write(char)
sys.stdout.flush()
break
But this prints the text and then 'hangs' at the end.
All suggestions welcome!
Related
I am testing below python code to export content from one txt file to another but in destination contents are getting copied with some different language (may be chinese) with improper
# - *- coding: utf- 8 - *-
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print "Does the output file exist ? %r" %exists(to_file)
print "If 'YES' hit Enter to proceed or terminate by CTRL+C "
raw_input('?')
infile=open(from_file)
file1=infile.read()
outfile=open(to_file,'w')
file2=outfile.write(file1)
infile.close()
outfile.close()
try this code to copy 1 file to another :
with open("from_file") as f:
with open("to_file", "w") as f1:
for line in f:
f1.write(line)
this is the current code:
import time
import sys
import os
sys.path.append(os.path.abspath("SO_site-packages"))
import pyperclip
recent_value = ""
while True:
tmp_value = pyperclip.paste()
if not tmp_value = recent_value:
recent_value = tmp_value
print("Value changed: %s" % str(recent_value)[:20])
time.sleep(0.1)
What I'm trying to do: create a constant loop that waits for a user to copy text to clipboard, and print it whenever that happens.
What happens currently: It only prints out the last copied item and stops.
My question is: How to make this code a listening loop?
Help will be deeply appreciated.
I'm trying to run a pygame program using pythonw to avoid having the console window show up. This causes a weird issue related to print statements.
Basically, the program will just exit after a few seconds with no error message. The more printing I do, the faster it happens.
If I run it in idle or at the command prompt (or in linux) the program works fine. This problem only happens when launched with pythonw (right-click, Open With, pythonw).
I'm using python 2.7.11 on Windows XP 32-bit. pygame 1.9.1release.
Is there a workaround for this? Why does the program simply terminate with no error?
import pygame
from pygame.locals import *
succeeded, failed = pygame.init()
display_surface = pygame.display.set_mode((320, 240))
clock = pygame.time.Clock()
terminate = False
while terminate is False:
for event in pygame.event.get():
if event.type == QUIT:
terminate = True
area = display_surface.fill((0,100,0))
pygame.display.flip()
elapsed = clock.tick(20)
print str(elapsed)*20
pygame.quit()
You don't need to remove print statements. Save them for later debugging. ;-)
Two steps to solve this problem:
Firstly, keep all the code in py file - don't change it to pyw now; Say it is actualCode.py
Then, create a new file runAs.pyw with the following lines in it
# In runAs.pyw file, we will first send stdout to StringIO so that it is not printed
import sys # access to stdout
import StringIO # StringIO implements a file like class without the need of disc
sys.stdout = StringIO.StringIO() # sends stdout to StringIO (not printed anymore)
import actualCode # or whatever the name of your file is, see further details below
Note that, just importing actualCode runs the file, so, in actualCode.py you should not enclose the code which is executed, in what I call is it main running file condition. For example,
# In actualCode.py file
....
....
....
if __name__ == '__main__': # Don't use this condition; it evaluates to false when imported
... # These lines won't be executed when this file is imported,
... # So, keep these lines outside
# Note: The file in your question, as it is, is fine
I am writing a program in Python to run on my Raspberry Pi. As many people knows, Raspberry can receive many ways of input. I am using a keyboard and another external input source. This is just for contextualize, not really important for the question itself.
On my program, I wait for a keyboard input and if there is none during a short period of time, I skip and look for the input from the other source. In order to do this I am using the following code:
import sys
import time
from select import select
timeout = 4
prompt = "Type any number from 0 up to 9"
default = 99
def input_with(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
s = int(sys.stdin.read().replace('\n',''))
else:
s = default
print s
return s
I am going to run the Raspberry Pi without a full keyboard, this means I won't have the return key. It will be impossible to validate the keyboard input on this way.
My doubt is if it is possible to get the user input without pressing enter and keeping the timeout for the input.
I've seen many topics talking about both issues (timeout and input without pressing return) but nothing with both together.
Thanks in advance for any help !
I don't think it is straightforward to do it the way you want i.e. to read the waiting contents on the line, even if enter hasn't been pressed (that's right?).
The best suggestion I can offer is that you capture each character as it is pressed, and invoke once the time has passed. You can capture input on a per character basis by setting cbreak mode: tty.setcbreak()
import sys
from select import select
import tty
import termios
try:
# more correct to use monotonic time where available ...
from time33 import clock_gettime
def time(): return clock_gettime(0)
except ImportError:
# ... but plain old 'time' may be good enough if not.
from time import time
timeout = 4
prompt = "Type any number from 0 up to 9"
default = 99
def input_with(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
# store terminal settings
old_settings = termios.tcgetattr(sys.stdin)
buff = ''
try:
tty.setcbreak(sys.stdin) # flush per-character
break_time = time() + timeout
while True:
rlist, _, _ = select([sys.stdin], [], [], break_time - time())
if rlist:
c = sys.stdin.read(1)
# swallow CR (in case running on Windows)
if c == '\r':
continue
# newline EOL or EOF are also end of input
if c in ('\n', None, '\x04'):
break # newline is also end of input
buff += c
sys.stdout.write(c) # echo back
sys.stdout.flush()
else: # must have timed out
break
finally:
# put terminal back the way it was
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
if buff:
return int(buff.replace('\n','').strip())
else:
sys.stdout.write('%d' % default)
return default
How can I print out the output of an external command by characters or at least by lines?
This code prints it in one block after the command returns.
import subprocess as sub
output, errors = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True).communicate()
print output + errors
You can access to the standart output stream as
p = sub.Popen("cmd", stdout=sub.PIPE, stderr=sub.PIPE)
print(p.stdout.readline()) # This read a line
You can perform any operation o the file streams.
When you use readline in a standart output of a proccess the main thread of the app wait for that proccess to write some thing on the ouput. When that process write to the output you program continue.
You must know that before read a line from the proceess you need to call flush() on the stream. Because the streams have a cache time before the real values are written to it.
You can see this post, this is a good explanation of how this work on python
http://www.cyberciti.biz/faq/python-execute-unix-linux-command-examples/
import subprocess
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
It prints out the output of the cmd character by character.