I have two functions prints() and clear(). The function prints() print lines of text and the function clear() delete the printed lines with this method:
def clear():
i = 0
while True:
if(i > globals['l']):
break
else:
sys.stdout.write("\033[F \033[K")
i += 1
where globals['l'] is the number of lines to clear.
Then after the function clear() runs and the lines are cleared, the function prints() run again etc...
I don't understand why the function clear() is clearing only 22 lines of 32 lines. But if I have, for example, 19 lines it is working perfectly. Where is the problem? How can I fix this?
Try this:
def clear(line_count):
sys.stdout.write("\033[F \033[K" * line_count)
sys.stdout.flush()
EDIT:
Works only on Unix systems
You can use:
print("\033c")
Or:
import subprocess
subprocess.call(["printf", "\033c"])
Related
I am currently working on a function that is to loop through a list of functions and then restart back at the top once it reaches the bottom. So far this is the code that I have:
import time
createLimit = 100
proxyFile = 'proxies.txt'
def getProxies():
proxyList = []
with open(proxyFile, 'r') as f:
for line in f:
proxyList.append(line)
return proxyList
proxyList = getProxies()
def loopProxySwitch():
print("running")
current_run = 0
while current_run <= createLimit:
if current_run >= len(proxyList):
lengthOfList = len(proxyList)
useProxy = proxyList[current_run%lengthOfList]
print("Current Ip: "+useProxy)
print("Current Run: "+current_run)
print("Using modulus")
return useProxy
else:
useProxy = proxyList[current_run]
print("Current Ip: "+useProxy)
print("Current Run: "+current_run)
return useProxy
time.sleep(2)
print("Script ran")
loopProxySwitch()
The problem that I am having is that the loopProxySwitch function does not return or print anything within the while loop, however I don't see how it would be false. Here is the format of the text file with fake proxies:
111.111.111.111:2222
333.333.333.333:4444
444.444.444.444:5555
777.777.777.777:8888
919.919.919.919:0000
Any advice on this situation? I intend to incorporate this into a program that I am working on, however instead of cycling through the file on a timed interval, it would only loop on a certain returned condition (such as a another function letting the loop function know that some function has ran and that it is time to switch to the next proxy). If this is a bit confusing, I will be happy to elaborate and clear any confusion. Any suggestions, ideas, or fixes are appreciated. Thanks!
EDIT: Thanks to the comments below, I fixed the printing issue. However, the function does not loop through all the proxies... Any suggestions?
Nothing is printed because you return something before printing.
The loop will break the first time condition is met as it will return a value and exit the function without reaching the print statements(functions) and/or the next iteration.
BTW if you actually want to print the returned value you can print the function itself:
print(loopProxySwitch())
I'm making a script that show you a question, you give the answer ("y" or "n") and the line is restarted, and appears another question. I've tried this (assuming that the number is the question)
import sys
for i in range (10):
sys.stdout.write('\r'+str(i))
label = input()
if label=='n':
doSomething
if label=='y':
doSomethingElse
but in this cases, I get this
0n
1n
2y
3n
and I want that if I have
0
I give my answer and press Enter, the currently line disappear and the new number appears
1
and then I give an answer again, and so on.
I've already check this question and this. I'm using python 3.5.
Edit:
Thanks to an answer, now I know that I need to avoid the '\n' of the input() function.
When you use input(),there always have a output with '\n'. This '\n' changed to a new line,then the '\r' can't work as you wanted.
So, Maybe you should break through here(the input()).
Maybe a \n like in (see Part 1) and you can use an elif (see Part 2)
for i in range (10):
sys.stdout.write(str(i) + '\n') # Part 1
label = input()
if label == 'n':
doSomething
elif label =='y': # Part 2
doSomething
I've started working on a small game. I've created a function that breaks all the code that follows it. Here's the full function:
def printBoard(currentBoard):
#Prints out the game board
for x in range(5):
#prints out 50 character line x
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
although it still works with just this:
def printBoard(currentBoard):
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
even things like:
print("Hello")
won't work after it. I've tried switching around variable names and such but the error the error still remains.
Looks like you are missing a closing ")"
Your indentation is wrong, change the function to this:
def printBoard(currentBoard):
#Prints out the game board
for x in range(5):
#prints out 50 character line x
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
I would like to make a program that will print out number values. I want it to display the number, then replace it with another number. A little like this:
val = 0
for looper in range(1, 10):
val += 1
print (val)
#Code to replace old number to new number
Thanks for helping!
If you want in-place update of the number, you can use \r.
import sys
val = 0
for looper in range(1, 10):
val += 1
sys.stdout.write("\r%d" % (val))
sys.stdout.flush()
time.sleep(1) # sleep added so that you can see the effect
Seems like you're looking for something to replace output in sys.stdout.
This is limited without using external libraries but you can do something like this:
import sys
import time
for number in xrange(10):
# put number in 'stdout'
sys.stdout.write(str(number))
# empty stdout (by default it waits for a new line)
sys.stdout.flush()
# display the number for some time
time.sleep(1)
# go back to beginning of input to override existing output
sys.stdout.write('\r')
I think you are taking about carriage return
use "\r" this with time.sleep(ms)
On Python 3, #Teemu Kurppa's answer could be written as:
import time
for i in range(1, 11):
print(i, end='\r', flush=True)
time.sleep(1)
Im not sure about the best way to do this but I have a python script saved as a .py. The final output of this script is two files x1.txt and y1.txt.
Basically I want to run this script say 1000 times and each run write my two text files with new names i.e x1.txt + y1.txt then second run x2.txt and y2.txt.
Thinking about this it seems it might be better to start the whole script with something like
runs=xrange(:999)
for i in runs:
##run the script
and then finish with something that does
for i in runs:
filnameA=prefix += "a"+i
open("filnamea.txt", "w").write('\n'.join('\t'.join(x for x in g if x) for g in grouper(7, values)))
for i in runs:
filnameB=prefix += "a"+i
open("filnameB.txt", "w").write('\n'.join('\t'.join(x for x in g if x) for g in grouper(7, values)))
Is this really the best way to do it? I bet its not..better ideas?
I know you can import time and write a filename that mathes time but this would be annoying for processing later.
If your computer has the resources to run these in parallel, you can use multiprocessing to do it. Otherwise use a loop to execute them sequentially.
Your question isn't quite explicit about which part you're stuck with. Do you just need advice about whether you should use a loop? If yes, my answer is above. Or do you also need help with forming the filenames? You can do that part like this:
import sys
def myscript(iteration_number):
xfile_name = "x%d.txt" % iteration_number
yfile_name = "y%d.txt" % iteration_number
with open(xfile_name, "w") as xf:
with open(yfile_name, "w") as yf:
... whatever your script does goes here
def main(unused_command_line_args):
for i in xrange(1000):
myscript(i)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
import subprocess
import sys
script_name = 'dummy_file.py'
output_prefix = 'out'
n_iter = 5
for i in range(n_iter):
output_file = output_prefix + '_' + str(i) + '.txt'
sys.stdout = open(output_file, 'w')
subprocess.call(['python', script_name], stdout=sys.stdout, stderr=subprocess.STDOUT)
On running this, you'll get 5 output text files (out_0.txt, ..., out_4.txt)
I'm not sure, but maybe, it can help:
Suppose, I want to print 'hello' 10 times, without manually writing it 10 times. For doing this, I can define a function :
#Function for printing hello 10 times:
def func(x):
x="hello"
i=1
while i<10 :
print(x)
i += 1
else :
print(x)
print(func(1))