I am trying to build a test script to test my python code.
The tested code should read from stdin and write to stdout.
The tester code should call the tested code passing the values in a file as stdin, and read stdout to compare with the expected values (stored in another file)
Tested code:
n = int(input())
x1,y1 = list(map(int, input().rstrip().split()))
x2,y2 = list(map(int, input().rstrip().split()))
#what it does is really not importante
if ((min(x1, x2) <= n/2) and (max(x1, x2) > n/2) or
(min(y1, y2) <= n/2) and (max(y1, y2) > n/2)):
print('S')
else :
print ('N')
Tester code:
import os
import subprocess as sp
inputs = os.listdir("./warmup_tests/warmup_B/input")
for ipt in inputs:
with open('./warmup_tests/warmup_B/input/{}'.format(ipt)) as f:
res = (sp.run(['python', 'b.py'], stdin=f, capture_output=True))
I have received multiple of the following error (when disabling capture_output to better visualization):
Traceback (most recent call last):
File "b.py", line 10, in <module>
x1,y1 = list(map(int, input().rstrip().split()))
File "<string>", line 1
5 2
^
SyntaxError: unexpected EOF while parsing
My input file is the following:
10
5 2
5 1
The above works when there is only one input() on the tested code. What am I missing for making it work with multiple input()?
Your code is work for me (with small changes). It works and with capture_output=True, and with capture_output=False
https://drive.google.com/open?id=16NK1_Qfdd98prpmBUqaP894j8uGTNdnf
command to run:
python3 tester.py
For your problem: I suspect in your input files can missing '\n' in some lines (may be editor bug, don't know).
Also try check indents in your module b.py
Can you share your code with input files for detailed analysing?
Related
when i use https://ideone.com
it gave me Runtime error how can i solve this ?
code :
a = int(raw_input())
b = int(raw_input())
c = int(raw_input())
z = a + b + c
print z
This is because on ideone for raw_input() you need to provide the inputs (click stdin or input to open the input entry box) BEFORE you actually run the program by pressing "Run" or "ideone it".
It is not an interactive shell like the python executable.
Sample: https://ideone.com/MvI72f
The actual runtime error being throw is :
Traceback (most recent call last):
File "prog.py", line 1, in <module>
EOFError: EOF when reading a line
I sometimes paste a list of commands to be executed in the Python interpreter (Interactive Mode (mirror)). By default, if one command fails (i.e., raises an error), the Python interpreter indicates the command has failed, then executes the subsequent commands.
Is there any way to configure the Python interpreter (Interactive Mode) so that it stops executing a list of commands whenever one command fails?
Answering the comments:
I am interested in Linux, Mac OS X and Microsoft Windows.
Code example that I paste in the Python interpreter:
1/0
print('yo')
I don't want yo to be printed, since 1/0 raises an error.
I paste the list of commands, from the clipboard, to the Python interpreter
You can extend InteractiveConsole and create your own shell which bails out on error. You can even run it from within interactive-mode :)
Here's a small example:
from code import InteractiveConsole
import sys
class Shell(InteractiveConsole):
def __init__(self):
self.stdout = sys.stdout
InteractiveConsole.__init__(self)
return
def runcode(self, code):
try:
exec code in self.locals
except:
self.showtraceback()
sys.exit(1) # <-- this is the secret sauce!
if __name__ == '__main__':
sh = Shell()
sh.interact()
OUTPUT
>>> sh = Shell()
>>> sh.interact()
Python 2.7.6 (default, Jan 26 2016, 22:37:40)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(Shell)
>>> 1
1
>>> 1+1
2
>>> 1/0
Traceback (most recent call last):
File "<console>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
alfasi:~/Desktop >
I'm not sure how to fix this on a standard Python REPL, but you can definitely achieve this with IPython.
In IPython, when you paste code, it is treated as a single code block, rather than a bunch of individual statements.
For example, open an IPython interactive session on your terminal and paste this:
x = [1]
y = [1 for _ in range(100)]] # <------ SyntaxError
z = x + y
This is what it looks like when pasted:
In [136]: x = [1]
...: y = [1 for _ in range(100)]]
...: z = x + y
Now hit enter:
File "<ipython-input-136-20c7b020310a>", line 2
y = [1 for _ in range(100)]]
^
SyntaxError: invalid syntax
In contrast, on the standard REPL interpreter:
>>> x = [1]
>>> y = [1 for _ in range(100)]]
File "<stdin>", line 1
y = [1 for _ in range(100)]]
^
SyntaxError: invalid syntax
>>> z = x + y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
Borrowing heavily from #alfasin's answer, you can extend the InteractiveConsole class.
To keep the interactive session running, but ignore the rest of the pasted commands, you can discard the input for a short while (I've used 1 second) after an exception. This means that the rest of the pasted commands are ignored, while leaving you with the session still running.
from code import InteractiveConsole
import sys
import time
WAIT_TIME = 1
class Shell(InteractiveConsole):
def __init__(self):
self.stdout = sys.stdout
InteractiveConsole.__init__(self)
return
def runcode(self, code):
try:
exec(code, self.locals)
except SystemExit:
raise
except:
self.showtraceback()
t_end = time.time() + WAIT_TIME
while time.time() < t_end:
_ = self.raw_input() # Extra pasted commands are discarded
if __name__ == '__main__':
sh = Shell()
sh.interact()
Note that the extra commands are still printed to the terminal, but aren't actually run.
def main():
name = input('Typer your name and press enter: ')
name_list = name.split()
print(name_list)
first = name_list[0][0]
middle = name_list[1][0]
last = name_list[2][0]
print(first.upper(),'.', middle.upper(),'.', last.upper())
main()
I am using python 3.5.2
You are running the code in Python 2, not Python 3... Observe
$ python script.py
Typer your name and press enter: ang go koms
Traceback (most recent call last):
File "script.py", line 13, in <module>
main()
File "script.py", line 2, in main
name = input('Typer your name and press enter: ')
File "<string>", line 1
ang go koms
^
SyntaxError: invalid syntax
Hence, your "error". Lookup the difference in input vs. raw_input... It's a common problem.
Now, try Python3
$ python3 script.py
Typer your name and press enter: ang go koms
['ang', 'go', 'koms']
A . G . K
You can see that my default python is actually Python 2
$ python --version
Python 2.7.13
I can't see any particular issue with the code you put up other than the missing colon. So this is what I have that run successfully. It seems you didn't copy paste the code you are running since you said you have the colon in your code. So maybe try mine and see if there is a difference somewhere character wise.
def main():
name = input('Type your name and press enter: ')
name_list = name.split()
print(name_list)
first = name_list[0][0]
middle = name_list[1][0]
last = name_list[2][0]
print(first.upper(), '.', middle.upper(), '.', last.upper())
main()
You may also want to look at handling when a name is longer or shorter than 3 words.
I recognize there are a decent amount of ValueError questions on here, but it seems none are specifically related to psychopy or my issue. I am coding an experiment from scratch on psychopy (no builder involved). Yesterday, my script was running totally fine. Today I tried running it without adding anything new or taking anything away and it's suddenly giving me this error:
File "/Users/vpam/Documents/fMRI_binding/VSTMbindingpaige.py", line 53, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
These are lines 52 and 53, apparently something in 53 (the last one) is making this happen, but I can't imagine what since it was working just fine yesterday. Anyone know why it's doing that? (I am running the oldest version of python in order to be able to include corrective audio feedback, but I have been running it on that with success):
from sys import argv
script, filename = argv
This is what I'm calling the filename (in the script it is above those other lines)
from sys import argv
script, filename = argv
from psychopy import gui
myDlg = gui.Dlg(title="Dr. S's experiment")
myDlg.addField('Subject ID','PJP')
ok_data = myDlg.show()
if myDlg.OK:
print(ok_data)
else:
print('user cancelled')
[sID]=myDlg.data
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
data_file = sID + '_VSTMbinding.txt'
f = open(data_file,'a') #name file here
f.write(sID)
print myDlg.data
It looks like you're using Python2. Python3 gives a more detailed information in it's error message. The problem is that argv only contains a single value and you're trying to unpack it into two variables. argv contains the command line variables -- if this was running yesterday "without any changes" as you suggest, it's because you were providing a filename as a command-line argument.
py2.py
#!/usr/bin/env python
from sys import argv
script, filename = argv
print("Script: {0}\nFilename: {1}".format(script, filename))
py3.py
#!/usr/bin/env python3
from sys import argv
script, filename = argv
print("Script: {0}\nFilename: {1}".format(script, filename))
Running py2.py:
$ charlie on laptop in ~
❯❯ ./py2.py
Traceback (most recent call last):
File "./py2.py", line 4, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
$ charlie on laptop in ~
❯❯ ./py2.py filename
Script: ./py2.py
Filename: filename
Running py3.py:
$ charlie on laptop in ~
❯❯ ./py3.py
Traceback (most recent call last):
File "./py3.py", line 4, in <module>
script, filename = argv
ValueError: not enough values to unpack (expected 2, got 1)
$ charlie on laptop in ~
❯❯ ./py3.py filename
Script: ./py3.py
Filename: filename
I've got a loop processing sockets, and I've set a pdb.set_trace() breakpoint to stop and inspect the results of the call to select.select() every time through the loop. However, there are also bugs elsewhere in my code, and it seems that the standard traceback is being overwritten by pdb.set_trace. As a result, when the program quits, the traceback points to the line immediately following the set_trace(), not the line that contained the error.
Is there a way to access the actual traceback, or does pdb.set_trace() clobber it?
Here's the relevant code snippet:
while True:
read_socks, write_socks, _ = select.select(all_sockets, all_sockets, '')
pdb.set_trace()
if listen_socket.fileno() in read_socks:
new_socket, address = listen_socket.accept()
id_num = new_socket.fileno()
all_sockets[id_num] = new_socket
for id_num in write_socks:
# do something that triggers an Assertion error
and then I get the traceback as follows:
Traceback (most recent call last):
File "socktactoe_server.py", line 62, in <module>
if listen_sock.fileno() in read_socks:
AssertionError
Here is a short reproducible test case; run it, hit c every time there is a breakpoint, after the second continue the assert raises an exception and it's reported for the wrong line:
import pdb
x = 0
while True:
pdb.set_trace()
y = "line of code not triggering an error"
x += 1
assert x != 3
Output:
Traceback (most recent call last):
File "minimal_pdb_traceback.py", line 7, in <module>
y = "line of code not triggering an error"
AssertionError
It looks like you found a bug in the Python pdb module! I can reproduce your simple case in Python versions 2.7, 3.2 and 3.3, while the problem is not present in Python 2.4, 2.5, 2.6 or 3.1.
At first glance, I don't see a preexisting bug in the python bug tracker. Please report your problem there, with your minimal test case, as well as what python versions it can be reproduced on.