Python raw_input() unable to paste in windows? - python

Is there a simple module that let's you paste input in python ?
Asking someone to type letter by letter is kinda harsh .
By default a .py file is opened with python.exe if is installed and this does not allow "rightclick+paste" in the console .So how can i make this happen with python ? i think this would be more of a exact question .

You can make this by open cmd.exe and type here "C:\Python32\python".
Path is depend on the version of python. Mine is 3.2.

If you're looking for a way to simply paste something into the windows command prompt, John Giotta is correct that a user can click on the little icon in the top left.
I imagine, however, that you're looking for a way that a user can input a large amount of text, without typing it in line by line. A simple way to do this, would be to let the user input a file name, which python would then read. Perhaps something like this is what you're looking for:
while True:
filename = raw_input("Path to file to be read: ")
try:
with open(filename, 'rb') as f:
contents = f.read()
break
except IOError:
print "That was not a valid file \n"
This loop will keep asking the user for a file until then enter a valid path. When they enter a valid path, it will be read in as a string to the contents variable. This way, a user could enter a large amount of text into a file, and then you simply prompt them for the path to the file.
You can read up on file input more In the docs.

Related

Why do some online Python compilers not allow me to enter an input?

I found quite a few examples of how to use input in Python 3. I even directly copied examples from videos to online python compilers and I always get an EOF error on the input line.
For example:
password = input("please enter password... ")
it won't even let me put an input and end the program. Did a rule change?
No, the input rules did not change.
It's just those type of online Python interpreters expect you to provide the input values before you actually run the program. There is no prompt for the input value, where they wait for you to enter something. Instead, they automatically read what you put for STDIN and then pass it to your program.
In https://onecompiler.com:
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab.
In https://www.tutorialspoint.com:
I would say it's better to learn how to run your programs locally, especially if you are writing programs that get or read multiple user inputs. For example, in the images above, you'll have to add some unnecessary code to print out the name on a separate line or to handle multiple input's. On local, the same code works (and looks) better:
$ cat main.py
name = input("What's your name? ")
print(name)
$ python3 main.py
What's your name? gino
gino

Strange behavior when trying to create and write to a text file on macOS [duplicate]

This question already has answers here:
Convert UTF-8 with BOM to UTF-8 with no BOM in Python
(7 answers)
Closed last year.
I'm opening a plain text file, parsing it, and adding different lines to existing, empty string variables. I add these variables into a new variable that is a multi-line fstring. Trying to write the data to a new text file is not behaving as expected.
Reading the original file works fine. Text is properly parsed, variables populated.
The multi-line fstring variable seems fine. Prints normally. Even tried formatting it different ways which I show below.
When writing to a new file, that's where the strangeness starts. I've tried 2 ways:
Straight coding the open function with w or w+
Adding the above to a function and using that inside main()
The file is saved to disk with the correct name. Trying to double-click open in Finder produces nothing. Right-click to open produces nothing. Trying to move to trash with command+delete gives an error:
It sounds like the file goes to trash, but as the file disappears from the folder a new one is created with the same name in its place.
If I try to open in TextMate via File > Open, it opens as a blank file with no errors.
Since I can't get rid of the file, I have to delete the directory and create the directory again with the same name, or force delete in Terminal using rm. Restarting the system does not help. Relaunching Finder does nothing. Saving text files from other apps works fine. Directory is chmod 755.
If I copy an existing text file into the output directory, rename it to what the file is expected to be named, and let python overwrite the contents, it doesn't work either. The file modification date changes (and I see the file "blink" in Finder) but the contents remain the same. However, the file is not corrupted and opens normally.
If I do the same but delete the text inside of the copied file first, then run the script, python writes no data to the file, I can't open it by double-clicking on it, and I get error -43 again with the odd non-trashing behavior.
The strangest thing is this: if I add another with open() at the end of the script, and open the file that was just created and supposedly written to, and print its contents, the contents print. It's like when the script ends the file contents are being removed or its being corrupted somehow. Tried to close the file inside the script even though it's not needed, but same behavior persists.
Code:
Here's the code for writing:
FORMAT='utf-8'
OUTPUT_DIR = '/Path/To/SaveFolder'
# as a function
def write_to_file(content, fpath, name):
the_file = os.path.join(fpath, name)
with open(the_file, 'w+', encoding=FORMAT) as t:
t.write(content)
def main():
print(f" Writing File...\n")
filename = f"{pcode}_{author}_{title}_text.txt"
write_to_file(multiline_var, OUTPUT_DIR, filename)
# or hard coded in main()
def main():
print(f" Writing File...\n")
filename = f"{pcode}_{author}_{title}_text.txt"
the_file = os.path.join(OUTPUT_DIR, filename)
with open(the_file, 'w+', encoding=FORMAT) as t:
t.write(multiline_var)
I have tried using w w+ wt and wt+ and with and without encoding='utf-8'
Here is an example of multi-line fstring variable:
# using triple quotes
multiline_var = f"""
[PROJ-{pcode}] {full_title} by {author}
{description}
{URL}
{DIVIDER_1}
{TEXT_BLURB}
Some text here and then {SOME_MORE_TEXT}"
{DIVIDER_1}
{SOME_LINK}
"""
# or inside parens
multiline_var = (
f"[PROJ-{pcode}] {full_title} by {author}\n"
f"{description}\n\n"
f"{URL}\n"
f"{DIVIDER_1}\n"
f"{TEXT_BLURB}\n\n"
f"Some text here and then {SOME_MORE_TEXT}\n"
f"{DIVIDER_1}\n\n"
f"{SOME_LINK}"
)
Using exiftool on the text file shows the following, so it looks the data is there but must be corrupted:
File Size : 1797 bytes
File Modification Date/Time : 2021:12:31 15:55:39-05:00
File Access Date/Time : 2021:12:31 15:58:13-05:00
File Inode Change Date/Time : 2021:12:31 15:55:39-05:00
File Permissions : -rw-r--r--
File Type : TXT
File Type Extension : txt
MIME Type : text/plain
MIME Encoding : utf-8
Byte Order Mark : No
Newlines : Unix LF
Line Count : 55
Word Count : 181
Not sure what I'm doing wrong. VScode shows no syntax errors in the script. There are no errors in Terminal when running the script. Have I made some simple mistake in the above code? Maybe the fstring variable is causing a problem?
Thanks to #bnaecker for leading me to the solution to this problem.
It appeared that when creating/writing to a text file with a long name, Python can corrupt it. Not sure why, as I save long names for images with Python image libraries all the time. Using a short name like "MyFile.txt" it worked just fine, but that was a red herring.
I have updated this post with my journey to the final solution for using the long names that are needed for my project, though I'm not sure why the problem exists.
First Attempts:
So far creating using a short name and then renaming to a long one.... attempts have failed. I did notice that python is locking the file it creates and never unlocks it. Not sure if this is the problem. Setting chflags with os.system('chflags nouchg') command does not work, not even with sudo, and not even in the Terminal doing it manually.
Using os.rename() in Python corrupts the file
Using os.system('mv oldFile.txt newFile.txt') corrupts the file
Manually using mv command in Terminal corrupts the file
Manually changing the filename in the Finder does not (wtf?)
I kept looking for workarounds but nothing did the job.
Round 2:
Progress!
After much tinkering, I discovered a hidden character inside the file. I ran cat /path/longfilename.txt in Terminal, selected and copied the output and pasted into VScode. Here is what I saw:
Somehow a hidden character is getting into the project code number.
Pasting it into a Unicode search engine it came up as a ZERO WIDTH NO-BREAK SPACE also known in Unicode as EF BB BF. However, when pasting this symbol into TextMate it shows up as <U+FEFF> which is?...
The Byte Order Mark!
Opening a normal utf-8 text file in a hex editor also shows the files starting with EFBBBF for the BOM.
Now, the text file being read and parsed at first has no blank lines to start the file, so I added a line break, and also tried adding some spaces. This time when writing the file I could open it, however, after sending it to the trash, the same behavior occurred and the file was broken again. It seems that because other corrupted versions were in the trash, it added the symbol back to the file name for some reason.
So what appears to be happening, for whatever reason, when Python opens the text file I'm parsing that has no line break at the top, it seems to be grabbing the BOM from the file and adding that to the first variable which is grabbing the first line of the text file. Since that text is a number code that starts the file name, the BOM symbol is being added to the file name as well as the code inside the text file.
Just... wow
The Current Solution:
I have to leave a blank line at the start of the text file that I'm opening and parsing and a simple line break won't do it. I have no idea why this is. I added some spaces for good measure because randomly the BOM would be added to the variable and filename again. So far (knock on wood) as long as the first line of that initial file has some spaces and then a line break, and previous corrupted files have been deleted from the trash, a long file name can be used for all the files I'm creating and writing to without any problems.
This corruption even persists if I remove the encoding flag from both of the open functions I'm using (one to read and parse, the other to create and write).
If anyone knows why this is happening, please share. I've never seen it mentioned before. I'm not sure if it's a python 3.8 bug, a mac OS bug, the way TextMate wrote the original file, or a combination of these.
Correct Solution:
Thanks to #tripleee for the proper way to handle this, as I don't remember seeing this before, though I haven't been using python for very long.
In order to ignore the BOM, reading in the text file to be parsed with an encoding='utf-8-sig' does the job. Seems to be why it exists. :)
Problem solved.

Creating a new text file with python is not happening unless i press ENTER in shell window

Am new to python and am working on a script that take a sentence from a text file, check its spelling and return the result to a new text file. When I run the script, the shell window open and the new text file is not creating unless i press ENTER in the shell window. I want the creation to happend directly without pressing ENTER. How do I fix this? Thanks.
import sys
import nltk
import enchant
import os
from pathlib import Path
my_file=Path('C:/Users/HP/Documents/result.txt')
if my_file.is_file():
os.remove("C:/Users/HP/Documents/result.txt")
save_path='C:/Users/HP/Documents'
name_of_file=input("result.txt")
completeName=os.path.join(save_path,name_of_file+"result.txt")
file1=open(completeName,"w")
with open ("C:/Users/HP/Documents/test.txt") as myfile:
data=myfile.read().replace('\n','')
from enchant.checker import SpellChecker
chkr=SpellChecker("fr")
chkr.set_text(data)
for err in chkr:
var=("ERROR:",err.word)
file1.write(str(var))
file1.close()
else:
save_path='C:/Users/HP/Documents'
name_of_file=input("result.txt")
completeName=os.path.join(save_path,name_of_file+"result.txt")
file1=open(completeName,"w")
with open ("C:/Users/HP/Documents/test.txt") as myfile:
data=myfile.read().replace('\n','')
from enchant.checker import SpellChecker
chkr=SpellChecker("fr")
chkr.set_text(data)
for err in chkr:
var=("ERROR:",err.word)
file1.write(str(var))
file1.close()
Try removing input:
name_of_file="result.txt"
input is needed if you want user to enter the string from keyboard. Hence, your program waits for ENTER key to be pressed.
Remove the calls to input() which require the user to press enter to terminate the input, if any.
name_of_file=input("result.txt")
If the user just presses enter then name_of_file will be the empty string. However, since this user input is used to construct a path to a writable file, you should be careful of this entry as the user could type in something unexpected, e.g. ../, and the resulting output file would then be C:/Users/HP/Documents/../result.txt which might unintendedly (or perhaps intentionally) overwrite a different file.

I am getting a File not Found error on a simple Python open() function [duplicate]

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
Closed 9 months ago.
Here is the code I have boiled it down to a simple open(), the Open file input statement displays but the Close file does not. This runs in the Idle interface but not in the command line interface.
Both the program and the file (spelled correctly and all lower case) are on the desktop for this test. Does anyone see what is missing?open
# Read It
# Demonstrates reading from a text file
input("\n\nPress the enter key to Open file")
print("Opening and closing the file.")
text_file = open("nicole1.txt", "r")
input("\n\nPress the enter key to Close file")
text_file.close()
input("\n\nPress the enter key to exit.")
** Update, Ok I tried the absolute path and it was not successful. I have a copy of this on a flash drive. I ran it on a Windows XP box and a Windows 7 box and it ran just fine. I take the same flash drive and try and run it on a Windows10 Box and I get the problem. One comment asked if there was a traceback and there is and it basically indicates that the file does not exist. I am now trying to determine if this is a Windows 10 issue. Also, the code will run inside idle on both Windows Boxes (XP and Win10).
I had the same problem on Windows 10 and the solution was, as stupid as it sounds, to simply decrease the path length. Apparently, Windows (10) still has problems with very long paths in 2021 AD.
Well, besides the fact that I named it nicole1.txt.txt by accident initially (due to the way that Windows automatically uses extensions and Linux does not), it works perfectly fine for me using Windows 10 Home and Pro, and Ubuntu 16.04.
I simply just executed python test.py in the command prompt with test.py containing your script and making sure both files were in the same directory.
I cannot test it on any other Windows version, as I no longer use them.
Also, btw, you may want to rewrite your code to:
input("\n\nPress the enter key to Open file")
print("Opening and closing the file.")
with open("nicole1.txt", "r") as text_file:
input("\n\nPress the enter key to Close file")
text_file.close()
input("\n\nPress the enter key to exit.")
This way, you make sure the file is closed no matter what happens.
And yes, I know, technically speaking the file is closed twice.
How are you running this program?
If by command line, then put the file into same folder where the python file that contains this code is situated.
As others have pointed out, the issue is program is unable to find the file.
If you're running this via some IDE, then set working directory to this path. For example, Pycharm (and other Intellij IDEs) have this in "Edit Configuration".

Multiple lines user input in command-line Python application

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.

Categories