How could I set a break point in my tornado app?
I tried pdb, but Tornado app seams to be ignoring my pdb.set_trace() command in my app.
If you are running your app using foreman you would set you environment variable in .env file in root project folder.
Setting the below env variable in my .env file did the tick form me.
PYTHONUNBUFFERED=true
Now I can set code breakpoints in my app, and also print output to server logs while running the app using foreman.
Where did you put pdb.set_trace()...? This works for me:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import pdb
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
greeting = self.get_argument('greeting', 'Hello')
reself.write(greeting + ', friendly user!')
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
pdb.set_trace()
tornado.ioloop.IOLoop.instance().start()
Session:
$ python test.py
> /home/mariusz/Dokumenty/Projekty/Testy/test.py(24)<module>()
-> tornado.ioloop.IOLoop.instance().start()
(Pdb) break 16
Breakpoint 1 at /home/mariusz/Dokumenty/Projekty/Testy/test.py:16
(Pdb) continue
> /home/mariusz/Dokumenty/Projekty/Testy/test.py(16)get()
-> self.write(greeting + ', friendly user!')
(Pdb) step
--Call--
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(497)write()
-> def write(self, chunk):
(Pdb) step
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(512)write()
-> if self._finished:
(Pdb) step
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(516)write()
-> if isinstance(chunk, dict):
(Pdb)
After putting continue in above code debugger stopped, because I had to poll http://localhost:8000/ in browser to have RequestHandler function actually called.
Related
I uploaded micropython on to ESP32S2 MAGTAG board. But i have issue with error messages and some print() code. It looks like some print messages are just cut and also i don't see the whole traceback line if there was an error. Example1: (this shows how rint just hoops over some messages. In the below code it should show "Neopixel Initiated" but instead it shows only "Ne" and current RTC time which i display later in code).:
print("STARTING MY CODE")
import machine
import socket
import ure
import utime
import network
import urequests
import ntptime
import json
import time
import neopixel
print("STARTING Neopixel")
np=neopixel.NeoPixel(machine.Pin(1),4)
np_enable=machine.Pin(21)
np_enable=machine.Pin(21, machine.Pin.OUT)
np_enable.value(0)
np[0]=(2,0,0)
np[1]=(0,2,0)
np[2]=(0,0,8)
np[3]=(2,2,2)
np.write()
print("Neopixel Initiated")
print("STARTING MY 4")
print("STARTING MY CODE")
print("Runing MY CODE 1")
print("Runing MY CODE 2")
rtc=machine.RTC()
tim0=machine.Timer(0)
print("Runing MY CODE 3")
tim0.deinit()
print("RTC time:", rtc.datetime())
Output is:
Ready to download this file,please wait!
> .......................................................................................
> download ok exec(open('./main.py').read(),globals())
> STARTING MY CODE
> STARTING Neopixel
> Ne0, 3, 32, 53167)
> next message is printed from further in code
When i get an error i can't see traceback messages as on example here I intentionally placed error in "npi.write()":
> Ready to download this file,please wait!
> .......................................................................................
> download ok exec(open('./main.py').read(),globals())
> STARTING MY CODE
> STARTING Neopixel
> Trac >>>
I don't know if this has to do with buffering in python or EPS32S2 but it makes it impossible to debugg. Have been doing same project on ESP32 and there was no issue.
What can be done to solve it?
P.S i know it suppose to be circuit python for this pcb.
I'm trying to run a code from github that uses Python to classify images but I'm getting an error.
here is the code:
import argparse as ap
import cv2
import imutils
import numpy as np
import os
from sklearn.svm import LinearSVC
from sklearn.externals import joblib
from scipy.cluster.vq import *
# Get the path of the testing set
parser = ap.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-t", "--testingSet", help="Path to testing Set")
group.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')
args = vars(parser.parse_args())
# Get the path of the testing image(s) and store them in a list
image_paths = []
if args["testingSet"]:
test_path = args["testingSet"]
try:
testing_names = os.listdir(test_path)
except OSError:
print "No such directory {}\nCheck if the file exists".format(test_path)
exit()
for testing_name in testing_names:
dir = os.path.join(test_path, testing_name)
class_path = imutils.imlist(dir)
image_paths+=class_path
else:
image_paths = [args["image"]]
and this is the error message I'm getting
usage: getClass.py [-h]
(- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test TESTINGSET | - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg IMAGE)
[- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset]
getClass.py: error: one of the arguments - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/--testingSet - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg/--image is required
can you please help me with this? where and how should I write the file path?
This is an error your own program is issuing. The message is not about the file path but about the number of arguments. This line
group = parser.add_mutually_exclusive_group(required=True)
says that only one of your command-line arguments (-t, -i) is permitted. But it appears from the error message that you are supplying both --testingSet and --image on your command line.
Since you only have 3 arguments, I have to wonder if you really need argument groups at all.
To get your command line to work, drop the mutually-exclusive group and add the arguments to the parser directly.
parser.add_argument("-t", "--testingSet", help="Path to testing Set")
parser.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')
from pexpect import pxssh
import getpass
import time
import sys
s=pxssh.pxssh()
class Testinstall:
def setup_class(cls):
cls.s=pxssh.pxssh()
cls.s.login('10.10.62.253', 'User','PW',auto_prompt_reset=False)
def teardown_class(cls):
cls.s.logout()
def test_cleanup(cls):
cls.s.sendline('cat test.py')
cls.s.prompt(timeout=10)
cls.s.sendline('cat profiles.conf')
cls.s.prompt(timeout=10)
print('s.before')
print (cls.s.before)
print('s.after')
print(cls.s.after)
In above code print(cls.s.before) prints, output of both cat commands.
As per expectation it should only print output of the 2nd cat command i.e cat profiles.conf.
When tried in python session in shell it shows output of only second cat command ( as per expectation)
If you use auto_prompt_reset=False for pxssh.login() then you cannot use pxssh.prompt(). According to the doc:
pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute.
So for your code, both prompt() would time out and .before would have all output and .after would be pexpect.exceptions.TIMEOUT.
The doc also says that
Calling prompt() will erase the contents of the before attribute even if no prompt is ever matched.
but this is NOT true based on my testing:
>>> from pexpect import pxssh
>>> ssh = pxssh.pxssh()
>>> ssh.login('127.0.0.1', 'root', 'passwd')
True
>>> ssh.PROMPT = 'not-the-real-prompt'
>>> ssh.sendline('hello')
6
>>> ssh.prompt(timeout=1)
False
>>> ssh.before
'hello\r\n-bash: hello: command not found\r\n[PEXPECT]# '
>>> ssh.after
<class 'pexpect.exceptions.TIMEOUT'>
>>> ssh.sendline('world')
6
>>> ssh.prompt(timeout=1)
False
>>> ssh.before
'hello\r\n-bash: hello: command not found\r\n[PEXPECT]# world\r\n-bash: world: command not found\r\n[PEXPECT]# '
>>> ssh.after
<class 'pexpect.exceptions.TIMEOUT'>
>>>
From the result you can see .before is not erased for the 2nd prompt(). Instead it's appended with the new output.
You can use ssh.sync_original_prompt() instead of ssh.prompt().
Which is the best way of redirect the output of a command to a VTE terminal?
i came with this idea:
On the VTE execute:
tty > /usr/tmp/terminal_number
then read the file from the python program:
with open('/usr/tmp/terminal_number', 'r') as f:
self.VTE_redirect_path=f.readline()
then execute the bash commands, for exemple:
os.system('''echo "foo" > {0}'''.format(self.VTE_redirect_path))
The problem of this method is that the file terminal_number containing /dev/pts/# needs to be refreshed. Also i don't really like the idea of having to create files to communicate. Is there any direct solution?
#Quentin The solution that you gave me prints the console output really bad (it doesn't indents) so i had to use my solution. Here is a clear example:
from gi.repository import Gtk, GObject, Vte, GLib
import os, time, threading
def command_on_VTE(self,command):
length=len(command)
self.terminal.feed_child(command, length)
class TheWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="inherited cell renderer")
self.set_default_size(600, 300)
self.terminal=Vte.Terminal()
self.terminal.fork_command_full(
Vte.PtyFlags.DEFAULT, #default is fine
os.environ['HOME'], #where to start the command?
["/bin/bash"], #where is the emulator?
[], #it's ok to leave this list empty
GLib.SpawnFlags.DO_NOT_REAP_CHILD,
None, #at least None is required
None,
)
#set up the interface
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
#a scroll window is required for the terminal
scroller = Gtk.ScrolledWindow()
scroller.set_hexpand(True)
scroller.set_vexpand(True)
scroller.add(self.terminal)
box.pack_start(scroller, False, True, 2)
self.add(box)
#To get the command to automatically run
#a newline(\n) character is used at the end of the
#command string.
command_on_VTE(self,'''tty > /tmp/terminal_number\n''') # Get the terminal ID
# read the terminal ID
while not os.path.exists("/tmp/terminal_number"):
time.sleep(0.1)
with open('/tmp/terminal_number', 'r') as f:
self.VTE_redirect_path=f.readline()
os.remove('/tmp/terminal_number')
# this cleans the vte
os.system('''printf "\\033c" > {0}'''.format(self.VTE_redirect_path))
# this calls the exemple
threading.Thread(target=self.make_a_test).start()
def make_a_test(self):
os.system('''ls -laR /home/ > {rdc}
echo "-------- The listing ended -------
Note that the input of the commands are not printed
" > {rdc}'''.format(rdc=self.VTE_redirect_path))
win = TheWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
I haven't found a way of getting the Terminal ID with out passing for the creation of a temporary file. This could be skipped if there is some way to pass a variable from the VTE to the python script. Any help on this would be great!
In VTE you use terminal.feed("string")
See vte_terminal_feed.
With python Popen is the suggested method to execute commands.
If you are wanting to use commands then you should do this.
#Uncomment the next line to get the print() function of python 3
#from __future__ import print_function
import os
import subprocess
from subprocess import Popen
command = "echo \"something\""
env = os.environ.copy()
try:
po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
universal_newlines=True, env=env)
po.wait()
output, error_output = po.communicate()
if po.returncode:
print(error_output)
else:
print(output)
except OSError as e:
print('Execution failed:', e, file=sys.stderr)
If you want to use gtk with gtk vte then do this instead.
#place the following in a method of a vte instance
env = os.environ.copy()
try:
po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
universal_newlines=True, env=env)
po.wait()
output, error_output = po.communicate()
if po.returncode:
print(error_output)
else:
self.feed(output) #here you're printing to your terminal.
except OSError as e:
print('Execution failed:', e, file=sys.stderr)
For the finest control in a regular terminal you can try the cmd module. This will require that you produce your own prompt so it is a more specific option to get what you want.
I'm having problems compiling an executable for an application I made using:
- Python 3.3
- PyQT5
- Matplotlib
I tried using Cx_Freeze with this setup.py:
import sys
from cx_Freeze import setup, Executable
includes = ['sys','PyQt5.QtCore','PyQt5.QtGui', 'PyQt5.QtWidgets','matplotlib']
excludes = []
packages = []
path = []
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
options = {
'build_exe': {
"includes": includes,
"excludes": excludes,
"packages": packages,
"path": path
#'excludes': ['Tkinter'] # Sometimes a little finetuning is needed
}
}
executables = [Executable('pyqt5_matplotlib.py', base=base)]
setup(name='pyqt5_matplotlib',
version='0.1',
description='Sample PyQT5-matplotlib script',
executables=executables,
options=options
)
When running setup.py build a folder containing various dlls and the exe is created, no error at this time.
When running the exe thus created I get this error:
http://i.stack.imgur.com/D0nsq.jpg
Can anyone please help me?
For the purpose of this question I will include a sample main script that when built reproduces the error:
# #author: Sukhbinder Singh
#
# Simple QTpy and MatplotLib example with Zoom/Pan
#
# Built on the example provided at
# How to embed matplotib in pyqt - for Dummies
#
# http://stackoverflow.com/questions/12459811/how-to-embed-matplotib-in-pyqt-for-dummies
#
# """
import sys
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QWidget, QVBoxLayout )
from PyQt5.QtCore import pyqtSlot, QDir, Qt
from PyQt5 import QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
import numpy
import random
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
#self.toolbar.hide()
# Just some button
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
self.button1 = QPushButton('Zoom')
self.button1.clicked.connect(self.zoom)
self.button2 = QPushButton('Pan')
self.button2.clicked.connect(self.pan)
self.button3 = QPushButton('Home')
self.button3.clicked.connect(self.home)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
self.setLayout(layout)
def home(self):
self.toolbar.home()
def zoom(self):
self.toolbar.zoom()
def pan(self):
self.toolbar.pan()
def plot(self):
#''' plot some random stuff '''
#data = [random.random() for i in range(25)]
data_matrix = numpy.random.random((256,256))
ax = self.figure.add_subplot(111)
ax.hold(False)
#ax.plot(data, '*-')
ax.imshow(data_matrix)
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.setWindowTitle('Simple QTpy and MatplotLib example with Zoom/Pan')
main.show()
sys.exit(app.exec_())
After a more in depth research I did the following:
Installed PyWin32
Installed beta release of cx_Freeze (might not be necessary) https://bitbucket.org/anthony_tuininga/cx_freeze/downloads
edited python33/Lib/site-packages/matplotlib/mpl-data/matplotlibrc so that line 32:
backend: tkAgg
becomes
backend: Agg
last source was ImportError: No module named backend_tkagg
This solution works on Win 7 64bit with Python3.3 for a single window PyQT5 with Matplotlib backends.