How to debug function declared on Spyder IPython console - debugging

how do I debug and step into a function that I declared interactively on Spyder Ipython?
As an example, I have the following function that I declare interactively:
def my_function(x,y):
w = x*2
z = y*2
return w+z
I did some reading online, it looks like to debug I have to load the py script first. As an example:
$ python -m pdb hello.py
Can I debug without loading the script?
I want to call my_function(1,2) and see what values are the w and z.
Thank you!

You need to add the following line inside your function
def my_function(x,y):
import pdb; pdb.set_trace()
w = x*2
z = y*2
return w+z
Then after you call it in the console like this
my_function(1, 2)
you'll be taken to the debugger automatically.

Related

Why is the output file from Biopython not found?

I work with a Mac. I have been trying to make a multiple sequence alignment in Python using Muscle. This is the code I have been running:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="testunaligned.fasta", out="testunaligned.aln", clwstrict=True)
print(cline)
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)
I keep getting the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'testunaligned.aln'
Does anyone know how I could fix this? I am very new to Python and computer science in general, and I am totally at a loss. Thanks!
cline in your code is an instance of MuscleCommandline object that you initialized with all the parameters. After the initialization, this instance can run muscle, but it will only do that if you call it. That means you have to invoke cline()
When you simply print the cline object, it will return a string that corresponds to the command you can manually run on the command line to get the same result as when you invoke cline().
And here the working code:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(
input="testunaligned.fasta",
out="testunaligned.aln",
clwstrict=True
)
print(cline)
cline() # this is where mucle runs
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)

Tracing program/function execution on source line level

Is there a way, to record the execution of a particular function (or the entire program) in terms of the executed source code lines?
Consdier I set a breakpoint in gdb to function foo, and then repetedly call step, and it will tell me something like this:
(gdb) break foo
Thread 1 "main" hit Breakpoint 1, foo () at foo.cpp:10
(gdb) step
foo () at foo.cpp:12
(gdb) step
foo () at foo.cpp:13
(gdb) step
foo () at foo.cpp:12
(gdb) step
foo () at foo.cpp:14
Then I repeat that until foo is no longer in the output of bt. This gives me a trace of execution (foo.cpp:10->12->13->12->14), that is particularly useful to compare long control flows.
Is there a way to do this with gdb or is there another tool that does this? I am only interested in deterministic traces, not sampling. Ideally this could also be done for stepi (on instruction level) / next (without entering subroutines).
Based on this similar question, I was able to put together a quick python script for my purpose. Fortunately with less required bug-workarounds:
import sys
import gdb
import os
import re
def in_frames(needle):
""" Check if the passed frame is still on the current stack """
hay = gdb.newest_frame()
while hay:
if hay == needle:
return True
hay = hay.older()
return False
# Use this to reduce any kind of unwanted noise
def filter_step(output):
output = re.sub(r'^.*No such file or directory\.\n', r'', output, flags=re.M)
output = re.sub(r'^\d+\s+in\s+.*\n', r'', output, flags=re.M)
return output
def step_trace(filename=None, step="step"):
counter = 0
if filename:
output = ""
frame = gdb.newest_frame()
print("Stepping until end of {} # {}:{}".format(frame.name(), frame.function().symtab, frame.function().line))
while in_frames(frame):
counter += 1
if filename:
output += filter_step(gdb.execute(step, to_string=True))
else:
gdb.execute(step)
if filename:
with open(filename, "w") as file:
file.write(output)
print("Done stepping through {} lines.".format(counter))
To output a trace to a file
(gdb) source step_trace.py
(gdb) python step_trace("filename.log")
or directly
(gdb) source step_trace.py
(gdb) python step_trace()

Why cannot do I get syntax errors when trying to define functions in Erlang?

I am try to learn Erlang. I've installed a runtime but cannot get it working. The following code:
X = 3.
works, but none of the following statements work:
f(X)->X.
F() ->0.
F([])->[].
I get back 1: syntax error before: '->'. I tried the word_count from this tutorial. And I get the same error.
What is wrong here?
In REPL you have to use fun(...) -> ... end:
1> F = fun(X) -> X end.
#Fun<erl_eval.6.80484245>
2> F(42).
42
If you have code in file use c command:
1> c(word_count).
{ok,word_count}
2> word_count:word_count([]).
0
There is difference in sytax when writing functions in Erlang module and Erlang shell (REPL). As P_A mentioned you need to call as F = fun(X) -> X end, F("Echo").
Also note that function names are atoms so has to start with lowercase when you are writing in Erlang module. If you are serious about learning Erlang I would suggest you go through this.
You mentioned that you worked on F#. The basic difference between F# and Erlang in this case is that expression
let Lilo = [|5; 3; -3; 0; 0.5|];; Can be written directly in the file and executed. In Erlang it can only be done in Erlang shell and not inside a file.
So the expression you are trying should be inside a function inside a module with the same name as file. Consider test.erl file. Any function you export can be called from outside (shell).
-module(test).
-export([test/0]).
test() ->
Lilo = [5, 3, -3, 0, 0.5],
[X*2 || X <-Lilo].

Best Way of redirecting output to a VTE terminal

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.

dajaxice: passing an argument to a python function

Using Dajaxice I want to pass a parameter to a python function.
In the html file I have the following statement
<i class="icon"></i>
and in my ajax.ps file I have the function
#dajaxice_register
def sayhello(request, dir):
print(dir)
It works fine if I remove the second argument dir in both the html and the python file, but with having dir, I get the error message "Something goes wrong".
Does anybody know what could be the issue here?
if you use Python 3.*, then in module dajaxIce make the changes file venv/lib/python3.2/site-packages/dajaxice/views.py
def safe_dict(d):
"""
Recursively clone json structure with UTF-8 dictionary keys
http://www.gossamer-threads.com/lists/python/bugs/684379
"""
if isinstance(d, dict):
return dict([(k, safe_dict(v)) for k, v in d.items()])
elif isinstance(d, list):
return [safe_dict(x) for x in d]
else:
return d
change the sayhello to :
def sayhello(request):
my_dict=json.loads(request.POST['argv'])
dir=my_dict['dir']
print(dir)

Resources