Multiple lines user input in command-line Python application - python

Is there any easy way to handle multiple lines user input in command-line Python application?
I was looking for an answer without any result, because I don't want to:
read data from a file (I know, it's the easiest way);
create any GUI (let's stay with just a command line, OK?);
load text line by line (it should pasted at once, not typed and not pasted line by line);
work with each of lines separately (I'd like to have whole text as a string).
What I would like to achieve is to allow user pasting whole text (containing multiple lines) and capture the input as one string in entirely command-line tool. Is it possible in Python?
It would be great, if the solution worked both in Linux and Windows environments (I've heard that e.g. some solutions may cause problems due to the way cmd.exe works).

import sys
text = sys.stdin.read()
After pasting, you have to tell python that there is no more input by sending an end-of-file control character (ctrl+D in Linux, ctrl+Z followed by enter in Windows).
This method also works with pipes. If the above script is called paste.py, you can do
$ echo "hello" | python paste.py
and text will be equal to "hello\n". It's the same in windows:
C:\Python27>dir | python paste.py
The above command will save the output of dir to the text variable. There is no need to manually type an end-of-file character when the input is provided using pipes -- python will be notified automatically when the program creating the input has completed.

You could get the text from clipboard without any additional actions which raw_input() requires from a user to paste the multiline text:
import Tkinter
root = Tkinter.Tk()
root.withdraw()
text = root.clipboard_get()
root.destroy()
See also How do I copy a string to the clipboard on Windows using Python?

Use :
input = raw_input("Enter text")
These gets in input as a string all the input. So if you paste a whole text, all of it will be in the input variable.
EDIT: Apparently, this works only with Python Shell on Windows.

Related

python input() with wide characters (jp or cn) is not working properly on Mac terminal

Writing a small dialog on terminal, and it supposed to take unicode input.
When input, the first time looks okay, but if you delete the character using backspace, you cannot fully delete them.
reproduce:
create a py file test.py
write single line in this file input(), and save
run the file using python test.py
input any japanese or chinese sentences, e.g. 这是一个测试
then try use backspace to delete, it only can only delete to half of the sentence.
(py ver 3.8)
it seems the delete in the terminal only delete one ascii size, where each wide char takes two.
but in python console it does not have this problem.
any idea?
====
updates:
a screen record: https://drive.google.com/file/d/1_jXSF9FxJt4U9_4O-faMyoWPp9mQPdrH/view?usp=sharing
found same problem on Mac+Bash, Mac+Zsh, Ubuntu+Bash, Ubuntu+Konsole
Windows Dos works ok.

Get text from a program in Python

I would like to get the text from a program with Python, for example from notepad. Can I "request" this text, just like from a website? I thought about something like this:
A document in Notepad:
Hello World!
This is a text!
GetText.py:
get_text("notepad.exe")
>>> Hello World!\nThis is a text!
Is this possible?
No, you can't, not directly.
There are various accessibility, etc. APIs you could use to try and "read" the user interface of another program, but that's certainly a lot more involved than just a simple get_text() style call.
(And for Windows Notepad, you can enumerate the Notepad main window's child windows, find the edit/rich-text control it's using and send a WM_GETTEXT message (if my memory serves) and hope it sends you some of the current text back...)
You can open the file in read-mode and simply print each line of the file using a for loop:
a_file = open('notepad.exe', 'r')
for line in a_file:
print(line)
a_file.close() #Make sure you close whatever file you open
If you are using Jupyter Notebook, make sure notepad.exe is in the same directory as you have your notebook opened in.
Side note: If you have experience with the command line (e.g. Linux), you can also open it in a text editor like vim. There, you can more readily see and edit it.

Can't get working command line on prompt to work on subprocess

I need to extract text from a PDF. I tried the PyPDF2, but the textExtract method returned an encrypted text, even though the pdf is not encrypted acoording to the isEncrypted method.
So I moved on to trying accessing a program that does the job from the command prompt, so I could call it from python with the subprocess module. I found this program called textExtract, which did the job I wanted with the following command line on cmd:
"textextract.exe" "download.pdf" /to "download.txt"
However, when I tried running it with subprocess I couldn't get a 0 return code.
Here is the code I tried:
textextract = shlex.split(r'"textextract.exe" "download.pdf" /to "download.txt"')
subprocess.run(textextract)
I already tried it with shell=True, but it didn't work.
Can anyone help me?
I was able to get the following script to work from the command line after installing the PDF2Text Pilot application you're trying to use:
import shlex
import subprocess
args = shlex.split(r'"textextract.exe" "download.pdf" /to "download.txt"')
print('args:', args)
subprocess.run(args)
Sample screen output of running it from a command line session:
> C:\Python3\python run-textextract.py
args: ['textextract.exe', 'download.pdf', '/to', 'download.txt']
Progress:
Text from "download.pdf" has been successfully extracted...
Text extraction has been completed!
The above output was generated using Python 3.7.0.
I don't know if your use of spyder on anaconda affects things or not since I'm not familiar with it/them. If you continue to have problems with this, then, if it's possible, I suggest you see if you can get things working directly—i.e. running the the Python interpreter on the script manually from the command line similar to what's shown above. If that works, but using spyder doesn't, then you'll at least know the cause of the problem.
There's no need to build a string of quoted strings and then parse that back out to a list of strings. Just create a list and pass that:
command=["textextract.exe", "download.pdf", "/to", "download.txt"]
subprocess.run(command)
All that shlex.split is doing is creating a list by removing all of the quotes you had to add when creating the string in the first place. That's an extra step that provides no value over just creating the list yourself.

How do you send part of a command to vim(in Ex mode) using if_py?

I'm trying to open a file on Ctrl-f. If the command is
typed in the presence of an empty buffer 'None' then I
want the file to be opened in that buffer, but if there
is no empty buffer I'd like to open a new buffer using
:tabnew and then open the file in that.
For this purpose I have a function OpenFile which is
invoked.
function! OpenFile()
python << EOF
import vim
import re
buffer = vim.current.buffer
name = str(buffer.name)
if re.match('None', name):
vim.command(':e ')
else:
vim.command(':tabnew')
vim.command(':e ')
EOF
endfunction
"Open file
:map <C-f> :call OpenFile()<CR>
:imap <C-f> <Esc>:call OpenFile()<CR>
vim.command executes the command so this is equivalent to
:w!ENTER What I want to do is setup part of the command..
:e FILENAME ENTER
So I want to send the :e part in Ex mode via the
python-function and get the user to type the filename
and hit ENTER
First of all, why do you write this in Python? Sure, Vimscript is a bit strange (but since Vim 7 is has become a lot like Python), and you need to learn about the integration points, anyway, and this task has very little real logic in it.
This is easiest solved via a map-expression (:help map-expression):
:noremap <expr> <C-f> empty(bufname('')) ? ':edit ' : ':tabnew '
If you must, extract the conditional into a function and code it in Python, but I would recommend sticking to Vimscript, unless the logic is really complex or you could benefit from certain libraries.

How do I modify program files in Python?

In the actual window where I right code is there a way to insert part of the code into everyline that I already have. Like insert a comma into all lines at the first spot>?
You need a file editor, not python.
Install the appropriate VIM variant for your operating system
Open the file you want to modify using VIM
Type: :%s/^/,/
Type: :wq
If you are in UNIX environment, open up a terminal, cd to the directory your file is in and use the sed command. I think this may work:
sed "s/\n/\n,/" your_filename.py > new_filename.py
What this says is to replace all \n (newline character) to \n, (newline character + comma character) in your_filename.py and to output the result into new_filename.py.
UPDATE: This is much better:
sed "s/^/,/" your_filename.py > new_filename.py
This is very similar to the previous example, however we use the regular expression token ^ which matches the beginning of each line (and $ is the symbol for end).
There are chances this doesn't work or that it doesn't even apply to you because you didn't really provide that much information in your question (and I would have just commented on it, but I can't because I don't have enough reputation or something). Good luck.
Are you talking about the interactive shell? (a.k.a. opening up a prompt and typing python)? You can't go back and edit what those previous commands did (as they have been executed), but you can hit the up arrow to flip through those commands to edit and reexecute them.
If you're doing anything very long, the best bet is to write your program into your text editor of choice, save that file, then launch it.
Adding a comma to the start of every line with Python:
import sys
src = open(sys.argv[1])
dest = open('withcommas-' + sys.argv[1],'w')
for line in src:
dest.write(',' + line)
src.close()
dest.close()
Call like so: C:\Scripts>python commaz.py cc.py. This is a bizzare thing to do, but who am I to argue.
Code is data. You could do this like you would with any other text file. Open the file, read the line, stick a comma on the front of it, then write it back to file.
Also, most modern IDEs/text editors have the ability to define macros. You could post a question asking for specific help for your editor. For example, in Emacs I would use C-x ( to start defining a macro, then ',' to write a comma, then C-b C-n to go back a character and down a line, then C-x ) to end my macro. I could then run this macro with C-x e, pressing e to execute it an additional time.

Categories