raw_input() does not run correctly because syntaxeror - python

I get this message when running the code:
Python 3.py 3.txt
I'm going to open the your file SMARTIE boy!
If you don't want that - press CONTROL_C-C
If you do want that- Press RETURN
Now i'm actually gonna do it
Now we're gonna truncate it
Write something for your beautiful day.
Traceback (most recent call last):
File "3.py", line 19, in <module>
line1 = raw_input("wefew")
TypeError: 'str' object is not callable
i don't know why
from sys import argv
script, filename = argv
print "I'm going to open the your file SMARTIE boy!"
print "If you don't want that - press CONTROL_C-C"
print "If you do want that- Press RETURN"
raw_input = ("<3")
print "Now i'm actually gonna do it"
mission = open(filename, 'w')
print "Now we're gonna truncate it"
mission.truncate()
print "Write something for your beautiful day."
line1 = raw_input("wefew")
line2 = raw_input("fwefw")
mission.write(line1)
print "Well done! let's close the file now"
mission.close()
Another question - After the code run well how can I print the txt file i changed?
Thanks :)

You are shadowing the raw_input function here: raw_input = ("<3"). That's why you cannot use the original function later on. You probably meant to just call the function:
raw_input("<3")
Another question - After the code run well how can I print the txt file i changed?
Open the file again, read and print the contents.
Suggestion: try reading about the context manager concept that handles opening and closing file objects for you:
with open(filename) as textfile:
print(textfile.read())

Related

CS50 taqueria task - input of eof halts program

I am trying to solve the taqueria task for the Harvard CS50 python course. It generally works, but check50 spits out the following:
:( input of EOF halts program
Cause
expected exit code 0, not 1
This is my code:
menu = {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00
}
def main():
item = get_dish("Item: ")
total = 0
try:
while True:
try:
total += menu[item.title()]
print("$" + str(round(total, 3)))
item = get_dish("Item: ")
except KeyError:
item = get_dish("Item: ")
pass
except EOFError:
pass
def get_dish(prompt):
dish = input(prompt)
while dish.lower() in menu == False:
dish = input(prompt)
else:
return dish
main()
I cannot end input to induce an EOFError in VS Code on GitHub myself by pressing ctrl + z or ctrl + d. Therefore, I cannot handle it myself in the try... except block. It might be a problem with the VS Code itself. Maybe there are other ways to end input, induce an EORError and handle it in the code.
Method 1: provide an empty input file
You can reproduce an EOFError in your code by giving it an empty input file.
In the VSCode terminal using bash, or at a bash prompt:
$ python script_name.py < /dev/null
Item: Traceback (most recent call last):
File "C:\Users\me\sandboxes\scratch\script_name.py", line 35, in <module>
main()
File "C:\Users\me\sandboxes\scratch\script_name.py", line 14, in main
item = get_dish("Item: ")
File "C:\Users\me\sandboxes\scratch\script_name.py", line 29, in get_dish
dish = input(prompt)
EOFError: EOF when reading a line
Or if you're using the Windows cmd prompt, in a VSCode terminal or otherwise:
> python script_name.py < NUL
Item: Traceback (most recent call last):
File "C:\Users\me\sandboxes\scratch\script_name.py", line 35, in <module>
main()
File "C:\Users\me\sandboxes\scratch\script_name.py", line 14, in main
item = get_dish("Item: ")
File "C:\Users\me\sandboxes\scratch\script_name.py", line 29, in get_dish
dish = input(prompt)
EOFError
In both cases above, you could also create a file to use as input, and have it empty when that's what you want to test, but /dev/null / NUL is the bash/cmd name for the special system empty file you can always use instead of creating one.
And as you see in these traces, the problem is that your first call to get_dish() is not in a try/except block.
Method 2: interactively end the input stream
In cmd, just type ^Z+Enter and that'll trigger the EOF and reproduce the same error.
To my surprise, in bash the equivalent ^D doesn't automatically do the same thing. I expected it would, as is typical, but instead when you type ^D+Enter you get "\x04" as the string returned by input(). So I guess if your program wants to accept ^D+Enter to mean end of file, it would have to explicitly do so with a piece of logic like if dish == "\x04": raise EOFError in get_dish(), but I understand you're just trying to debug your code and reproduce the error check50 gives you, so this is not too helpful.
So... if you're working in a bash terminal, use method 1 above.
When you've got things working, you'll probably want to add something to get_dish() for the user to signify they're done, like accepting q to mean done, because as it is, your user won't be able to exit the program cleanly, at least not from a bash terminal.

Script writes in reverse

Sorry if I asked this wrong or formatted it wrong, this is my first time here.
Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:
Hi, my name
is bob.
But, it writes:
is bob.
Hi, my name
How can I fix this?
The code is here:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()
Nice puzzle. Why are the lines coming out in reverse? Because of output buffering:
When you write to a file, the system doesn't immediately commit your data to disk. This happens periodically (when the buffer is full), or when the file is closed. You never close f, so it is closed for you when f goes out of scope... which happens when the function editor() returns. But editor() calls itself recursively! So the first call to editor() is the last one to exit, and its output is the last to be committed to disk. Neat, eh?
To fix the problem, it is enough to close f as soon as you are done writing:
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.close() # don't forget the parentheses
Or the equivalent:
with open(usrtxtdir, "a") as f:
f.write(words + '\n')
But it's better to fix the organization of your program:
Use a loop to run editor(), not recursive calls.
An editor should be writing out the file at the end of the session, not with every line input. Consider collecting the user input in a list of lines, and writing everything out in one go at the end.
If you do want to write as you go, you should open the file only once, write repeatedly, then close it when done.
You need to close your file after writing, before you try to open it again. Otherwise your writes will not be finalized until the program is closed.
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
f.close() # your missing line!
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
If you replace:
f = open(usrtxtdir,"a")
f.write(words + '\n')
with:
with open(usrtxtdir,"a") as f:
f.write(words + '\n')
It comes out in order. Pretty much always use with open() for file access. It handles the closing of the files for you automatically, even in the event of a crash. Although you might consider taking text in memory and writing it only upon quit. But that's not really part of the problem at hand.
Python's file.write() documentation states: "Due to buffering, the string may not actually show up in the file until the flush() or close() method is called"
Since you're recursively reopening the file and writing to it before closing it (or flushing the buffer), the outer value ('Hi, my name') isn't yet written when the inner frame (where you write 'is bob.') completes, which appears to automatically flush the write buffer.
You should be able to add file.flush() to correct it like this:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.flush() # <----- ADD THIS LINE HERE -----< #
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()
Also, don't forget to close your file after you're done with it!

"TypeError: 'str' object is not callable" with raw_input

I'm doing the exercises from Zed Shaw's "Learn Python The Hard Way", and exercise 16 just does not seem to want to work:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# reading and writing files
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "Otherwise, press [ENTER] to proceed."
raw_input = ("?")
print "Opening the file...."
target = open(filename, 'w')
print "Truncating the file...."
target.truncate()
print "Enter three lines of input...."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Writing to the file...."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "Closing the file...."
target.close()
# end program
For whatever reason, every time I run it, it returns this:
mark#mark-KC880AA-ABA-m9150f:/media/KINGSTON/cis-115-09/LPTHW$ python ex16.py ex15Sample.txt
We're going to erase 'ex15Sample.txt'.
If you don't want that, hit CTRL-C (^C).
Otherwise, press [ENTER] to proceed.
Opening the file....
Truncating the file....
Enter three lines of input....
Traceback (most recent call last):
File "ex16.py", line 24, in <module>
line1 = raw_input("line 1: ")
TypeError: 'str' object is not callable
No matter what I do, the line1 variable seems to be causing the trouble. I've been at it for over an hour now. Any advice?
The code overwrite raw_input function in following line:
raw_input = ("?")
Remove that line.
Replace it with raw_input('?').
>>> raw_input('line 1:')
line 1:111
'111'
>>> raw_input = ('?')
>>> raw_input('line 1:')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

What is an output file in python

I'm starting to work on problems for google's Code Jam. However I there seams to be a problem with my submission. Whenever I submit I am told "Your output should start with 'Case #1: '". My output a print statement starts with ""Case #%s: %s"%(y + 1, p)" which says Case #1: ext... when I run my code.
I looked into it and it said "Your output should start with 'Case #1: ': If you get this message, make sure you did not upload the source file in place of the output file, and that you're outputting case numbers properly. The first line of the output file should always start with "Case #1:", followed by a space or the end of the line."
So what is an output file and how would I incorporate it into my code?
Extra info: This is my code I'm saving it as GoogleCode1.py and submitting that file. I wrote it in the IDLE.
import string
firstimput = raw_input ("cases ")
for y in range(int(first)):
nextimput = raw_input ("imput ")
firstlist = string.split(nextimput)
firstlist.reverse()
p = ""
for x in range(len(firstlist)):
p = p +firstlist[x] + " "
p = p [:-1]
print "Case #%s: %s"%(y + 1, p)
Run the script in a shell, and redirect the output.
python GoogleCode1.py > GoogleCode1.out
I/O redirection aside, the other way to do this would be to read from and write to various files. Lookup file handling in python
input_file = open('/path/to/input_file')
output_file = open('/path/to/output_file', 'w')
for line in input_file:
answer = myFunction(line)
output_file.write("Case #x: "+str(answer))
input_file.close()
output_file.close()
Cheers
Make sure you're submitting a file containing what your code outputs -- don't submit the code itself during a practice round.

how to interact with an external script(program)

there is a script that expects keyboard input,
i can call that script with os.system('./script') in python,
how is it possible to send back an input to the script from another calling script?
update:
the script is:
$ cat script
#!/usr/bin/python
for i in range(4):
name=raw_input('enter your name')
print 'Welcome %s :) ' % name
when i try without a for loop, it works but it shows the output only when the script quits.
>>> p = subprocess.Popen('./script',stdin=subprocess.PIPE)
>>> p.communicate('navras')
enter your nameWelcome navras :)
when i try it with the foor loop, it throws error, How to display the statements interactive as and when the stdout is updated with new print statements
>>> p.communicate('megna')
enter your nameWelcome megna :)
enter your nameTraceback (most recent call last):
File "./script", line 3, in <module>
name=raw_input('enter your name')
EOFError: EOF when reading a line
(None, None)
You can use subprocess instead of os.system:
p = subprocess.Popen('./script',stdin=subprocess.PIPE)
p.communicate('command')
its not testet
In fact, os.system and os.popen are now deprecated and subprocess is the recommended way to handle all sub process interaction.

Categories

Resources