I'm newbie in using curses lib. I want to make a python program (running in a DOS terminal) that can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there. I tried to call a shellscript from python to do it, but I beleive it may exist a better way for doing it.
If all you want to do is rewrite the current line, just print a return char "\r". For example, this prints "ABCdef":
# print 'abcdef' then backup to start of line, then print 'ABC'
# (then print the normal cr/lf that 'print' always does)
print "abcdef\rABC"
(Also helpful to know that you can suppress the cr/lf by ending your print with a trailing comma...)
.
Related
I'm trying to write a program that works like the website https://www.peteranswers.com/. That is, to display a character on the screen that is part of a previously written text, whichever is the character you type. My attempt is this:
f=open("text1.txt", "r")
g=open("text2.txt", "w")
while True:
a = input()
g.write(a)
c = f.read(1)
if not c or a == "$":
break
print (c)
f.close()
g.close()
It works, but I would like not to display the characters you type and not to have to press enter each time.
How could this be done? Does it exist a more straightforward way to accomplish this task?
I'm working on Python 3.7 and IDLE.
The site you link does not work for me. From the code, I presume that you want something that works like a password entry function. But you want the characters echoed to be taken from an existing text instead of being nothing or a stream of ' 's or '*'s.
If so, I recommend that you modify the appropriate function, for Unix or Windows, in the getpass module. Note that both echo suppressing functions require that sys.stdout == sys.stdout (== system terminal and not None). Neither echo anything, you would have to add that. Neither work when you run in an IDE, such as IDLE, that rebind sys.stdout to print to a GUI.
If you are on Windows, you should read https://docs.python.org/3/library/msvcrt.html#console-i-o. You would use putch to write bytes, or use both getwch and putwch to input and output unicode characters. On Unix, you will have to dig into the code yourself.
I would like to add a key map to VI. The idea is to yank text and pass it to a python code.
Subsequently this python code can be used to preform some manipulations on the yanked text contained in the buffer #"
To do so, I added the following line to .vimrc
:map <F2> :echo system("python /tmp/t.py ".shellescape(#")) <Enter>
By pressing F2 the python script would run the code with #" as input. The problem is, that the yanked buffer contains the end line \ is a column is yanked with <C-r>V.
The buffer looks like this for a column input
1.233\
1.111\
1.222
I would like to accomplish the following
1) Don't include \ in the yank buffer is possible
2) make the pyhon script globally visible from within VI. Right now, it has to be in the same folder as the VI file, or an absolute path is needed
The latter one can be properly done by placing the script in the python site packages and importing it, but I guess, that more knowledgeble people might have better ideas. I remember seeing this done, by putting the python script in a special Vi folder.
the python code:
import sys
def to_float(v):
if len(v)>0 and v != "":
try:
return float(v)
except ValueError:
#print('yanked wrong text 1 "%s" '%v)
try:
return float(v[:-1])
except ValueError:
#print('yanked wrong text 2 "%s" '%v)
return 0.
else :
return 0.
def func(v):
s=0.
for i in v[1].split():
#print('from py >> %s <<'%i)
s=s+to_float(i)
print(">>>Summ: %17.8E"%s)
func(sys.argv)
Python-inside-Vim (as long as it is properly set up). Just dump this into your .vimrc (and make sure you don't add any indent to anything between python and EOF):
python << EOF
import vim
def float_or_0(value):
try:
return float(value)
except:
return 0.0
def sum_column():
lines = vim.eval('#"').splitlines()
total = sum(float_or_0(x) for x in lines)
print(">>>Summ: %17.8E" % total)
EOF
xmap <F2> y:py sum_column()<Enter>
Select your column, and hit F2. Magic. No hassle with transfering text through shell command line.
Or, you could select one of the strategies from Quickly calculate the total of a column of numbers.
I am working on a Python script to automate some repetitive text-fiddling tasks I need to do. I use PyDev as a plugin for Eclipse as my IDE.
I need the script to accept user input pasted from the clipboard. The input will typically be many lines long, with many newline characters included.
I currently have the script asking for input as follows:
oldTableString = raw_input('Paste text of old table here:\n')
The console correctly displays the prompt and waits for user input. However, once I paste text into the console, it appears to interpret any newline characters in the pasted text as presses of the enter button, and executes the code as if the only input it received was the first line of the pasted text (before the first newline character), followed by a press of the enter key (which it interprets as a cue that I'm done giving it input).
I've confirmed that it's only reading the first line of the input via the following line:
print oldTableString
...which, as expected, prints out only the first line of whatever I paste into the console.
How can I get Eclipse to recognize that I want it to parse the entirety of what I paste into the console, newlines included, as a single string?
Thanks!
text = ""
tmp = raw_input("Enter text:\n")
while tmp != "":
text += tmp + "\n"
tmp = raw_input()
print text
This works but you have to press enter one more time.
What about reading directly from the clipboard or looping over every line until it receives a termination symbol or times out. Also, is it important to make it work under Eclipse? Does it work when executed directly?
I'm trying to have Python copy the contents of a .txt file into the bash terminal on OS X (10.10), but the line does not print until every single character of the line has been printed to the line. Is there any way to have Python print each line character-by-character, instead of line-by-line? My code is designed to wait between characters, but each line simply takes a long time to print:
while True:
character = text_file.read(1)
if not character: break
else:
sys.stdout.write(character)
time.sleep(0.050)
When I run this code in IDLE, the characters print one at a time. In Terminal, lines take several seconds to print, and each line prints all at once. Is there any way to reproduce the behavior I'm seeing in IDLE in Terminal?
Add sys.stdout.flush() after sys.stdout.write(character)
The reason should be that the output of stdout is buffered.
if you want remove new line at the end of the line.
you can simply
print character,
will remove the new line(\n).
Is it possible (not necessarly using python introspection) to print the source code of a script?
I want to execute a short python script that also print its source (so I can see which commands are executed).
The script is something like this:
command1()
#command2()
command3()
print some_variable_that_contain_src
The real application is that I want to run a script from IPython with the run -i magic and have as output the source (i.e. the commands executed). In this way I can check which commands are commented at every execution. Moreover, if executed in a Notebook I leave a trace of which commands have been used.
Solution
Using korylprince solution I end up with this one-liner to be put at the beginning of the script:
with open(__file__) as f: print '\n'.join(f.read().split('\n')[1:])
This will print the script source except the first line (that would be only noise). It's also easy to modify the slicing in order to print a different "slice" of the script.
If you want to print the whole file instead, the one-liner simplifies to:
with open(__file__) as f: print f.read()
As long as you're not doing anything crazy with packages, put this at the top of your script
with open(__file__) as f:
print f.read()
Which will read in the current file and print it out.
For python 3 make sure to use instead
print(f.read())
For the most simple answer:
import my_module
print open(my_module.__file__).read()
I also tried using the inspect package.
import inspect
import my_module
source_list = inspect.getsourcelines(my_module)
Will give you a list of strings with the source code defined in it
for line in source_list[0]:
print line
Will print out the entire source code in a readable manner