>>> while True:
... line = input('> ')
... if line == 'done' :
... break
... print(line)
... print( 'Done!' )
File "<stdin>", line 6
print( 'Done!' )
^^^^^
SyntaxError: invalid syntax**
For python 3 this code should give me a "Done!" response when the break statement "done" is reached. However, I keep getting a syntax error for the last line. I have tried to do it multiple ways and I can get the break order to work without the last statement, however, it never works where I include the last statement "print('Done!')" with the break statement done. I apologize, this is just simple code but I can't seem to get it to work. Ps, I fixed it to make it as I am supposed to be writing it, the while True statement was not supposed to be twice (my error in copying it here) along with the extra space on the fifth line. and I have tried
It's not the language, it's your IDE. It is only expecting a single statement and the lines that are subordinate to it, i.e. indented. Once you've reached the end of the indenting it expects a blank line and doesn't know what to do when you try to give another statement.
If that same sequence were part of a file it would do exactly what you expect. If you put it all into a function, the whole function body will be indented and that would work too.
Related
I am trying to read each line in proc.stdout.readline and send the lines over the network, for example:
data = b''
for line in iter(proc.stdout.readline, ''):
data += line
clientsocket.send(data)
When I run this code I seem to be stuck in a inifinite loop unable to escape to the line:
clientsocket.send(data)
Is there a more efficient way to read the data? I've tried also with a while loop and breaking 'if not line':
data = b''
while True:
line += proc.stdout.readline()
data += line
if not line:
break
clientsocket.send(data)
This seems to also produce the same results. Is there a more efficient way to read all of the data from proc.stdout.readline?
I've encountered the same very problem. The strange thing that in Python 2.7 it had no problem to converge and actually stop iterating.
During debug (in Python 3.5) I've noticed that all true lines returned with the '\n' character, whereas the line that wasn't suppose to arrive returned as an empty string, i.e. ''. So, I just added an if-clause checking against '' and breaking the loop if positive.
My final version looks as follows:
lines = []
for _line in iter(process.stdout.readline, b''):
if _line == '':
break
lines.append(_line)
One thing that might be worth to mention, is that I used universal_newlines=True argument upon subprocess.Popen(..) call.
The statement: iter(proc.stdout.readline, "") will do a blocking read until it recieves an EOF.
If you want to read all the lines, then you can just do:
data = b''
data = b"".join(proc.stdout.readlines())
There is no other solution than for the proc to produce lines faster.
If you want, you can read lines with timeout (i.e. you can wait to read a select number of characters, or timeout if that number of characters are not read).
Those answers can be found here:
https://stackoverflow.com/a/10759061/6400614 .
https://stackoverflow.com/a/5413588/6400614
Okay, I am building a little program that will help single out Nmap results:
#Python3.7.x
#
#
#
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')
report = "ScanTest.txt"
target_ip = "10.10.100.1"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "Network Distance:"
for num1,line in enumerate(fhand, 1):
line = line.rstrip()
if line.startswith(begins) and line.endswith(target_ip):
print(num1)
for num2,line in enumerate(fhand, 1):
line = line.rstrip()
if line.startswith(beginsend):
print(num2)
In my what im trying to do is get the first part of the scan results "target_ip" and with that i hope i can read the lines from there until there is a break in the line of the txt.
What this code does for me now is just get me the line number where i want to start.
In the second part of the code I tried getting the number of line for the last bit of text that i need. But it wont print. Im not sure if im going about this the right way or im not looking hard enough.
In short find my line and print until there is a break in the text.
The first loop exhausts all the lines in the file. When the second loop tries to run, there are no more lines to read and the loop exits immediately.
If you want the first loop to stop when it finds a matching line and allow the second loop to read the remaining lines, you can add a break statement in the if.
start_pattern = 'hello there'
end_pattern = 'goodblye now'
print_flag = False
with open('somefile.txt') as file:
for line in file:
if start_pattern in line:
print_flag = True
if print_flag:
print line
if end_pattern in line:
break
Does someone know what is wrong with this section of my code as it seems to cause errors. I'm new to programming so I'm not completely sure what's wrong.
menu = "Be Lenny's Friend?\n"
1. Yes\n\
2. No\n\
answer = int(input(menu))
if answer == 1:
print(" ( ͡° ͜ʖ ͡°): Yayyyy! We are going to be friends!")
elif answer == 2:
reason = input(" ( ͡° ʖ̯ ͡°): Why do you not want to be my friend :(")
Error message:
'unexpected character after line continuation character'
Here you have set the variable as a tuple of a string and... well that’s where things get confusing.
The backslash is a like continuation symbol as in you can then break the line and continue on and it would count as the same line. However what the interpreter sees is n: which makes no sense. That is what it is complaining about.
If you wanted to add a new line to the string itself, you could add the \n at the end of the string.
However, also note that if you printed the string using print in the vanilla form without any other arguments than the Adrianne itself, it will append a new line automatically. So if you do add the \n, it may still not be what you want when you print it out. Parameter can of course be changed in the print function to take care of that.
I'm not sure what you are trying to archive with ,\n\: at the end of the line, but this line of code will remove the syntax error:
menu = "Be Lenny's Friend?"
If you want to archive a new line after the string you need to move "\n" into the string like this:
menu = "Be Lenny's Friend?\n"
Edit:
This should work for you:
menu = "Be Lenny's Friend?\n\t1. Yes\n\t2. No\n"
answer = int(input(menu))
if answer == 1: print(" ( ͡° ͜ʖ ͡°): Yayyyy! We are going to be friends!")
elif answer == 2: reason = input(" ( ͡° ʖ̯ ͡°): Why do you not want to be my friend :(\n")
Following in my code in Python 3.5
one=[]
dict={}
for i in range(int(input())):
for j in range(9):
one.append(int(input()) #missing one ) <- Line 5
dict[1]='hello' # Line 7
print(dict)
And following is exception thrown.
I have left out a ) on Line 5, but error is shown to be on Line 7.
Is this a bug or there is explanation for showing error on wrong line no ?
The parser doesn't know (and really, cannot know) that you forgot the closing ). It only knows that after skipping the whitespace, it did not expect to find an identifier (dict, in this case) immediately following int(input()). You would get basically the same error message from the more obvious error
>>> one.append(int("3") dict[1]=3)
File "<stdin>", line 1
one.append(int("3") dict[1]=3)
^
SyntaxError: invalid syntax
The similar code
for i in range(int(input())):
for j in range(9):
one.append(int(input())
+ dict[1])
would be fine, since indentation is flexible inside the unclosed parentheses. The parser isn't responsible for guessing which parentheses might be accidentally left open; it just reports where it first finds something that isn't grammatically valid in the current context.
This code works when I try it from a .py file, but fails in the command line interpreter and Idle.
>>> try:
... fsock = open("/bla")
... except IOError:
... print "Caught"
... print "continue"
File "<stdin>", line 5
print "continue"
^
SyntaxError: invalid syntax
I'm using python 2.6
With Python 3, print is a function and not a statement, so you would need parentheses around the arguments, as in print("continue"), if you were using Python 3.
The caret, however, is pointing to an earlier position than it would be with Python 3, so you must be using Python 2.x instead. In this case, the error is because you are entering this in the interactive interpreter, and it needs a little "help" to figure out what you are trying to tell it. Enter a blank line after the previous block, so that it can decipher the indentation properly, as in this:
>>> try:
... fsock = open("/bla")
... except IOError:
... print "Caught"
...
(some output shows here)
>>> print "continue"
You need to leave a blank line to close the except block. The ... indicates it is still trying to put code in that block, even though you dedent it. This is just a quirk of the interactive interpreter.
Try this one in the interpreter:
try:
fsock = open("/bla")
except IOError:
print "Caught"
print "continue"
Important here is the empty line after the indentation. I'm using the python 2.6 interpreter and it throws the same Syntax error as you.
This is because the interpreter expects single blocks separated by blank lines. Additionally the blank line (two new line characters) indicates the end of the block and that the interpreter should execute it.
Like if/else or for or while, try/except is a compound statement. In a Python shell prompt, statements after control keywords: ... need to be indented because the statement or compound statement is executed one by one. Your last print("continue") is aligned with the top-level try: and considered another statement hence syntax error.
If you want to test out try/except/else/finally interactively, you can wrap them in a function:
>>> def t():
... try:
... print(x)
... except:
... print('exception')
... return
... finally:
... print('finally')
... print('continue')
... print('end function t()')
...
>>> t()
exception
finally
>>> x = 99
>>> t()
99
finally
continue
end function t()
>>>
This was done with Windows python shell. When I tried on PyCharm IDE python console, it allows one more statement after the compound statement to execute.
>>> n = 0
>>> while n!= 5:
... n+=1
... print('n = {}'.format(n))
n = 5 # no syntax error
>>>