Get return value from running %run magics - ipython

My python script return a value(double type) and I run my script using %run magics,
for example: %run myScript.py
I would like to know I can I get the return value(double type) from running %run magics?

When using
%run myScript.py
any objects created while runing the script will be left in the current Ipython namespace.
So if myScript contains:
def foo(x):
return x*2
if __name__=='__main__':
y = foo(12.34)
Both foo and y will be available to you after the run.
Look at %run? for more options.

Related

Why are Julia benchmarks not shown in VSCode?

Hi Below is some simple code that displays the benchmark results form a Julia REPL. In VSCode I have tried
launching the Julia REPL from the Command Pallet and Running the file without Debugging
Execute the active File in Repl from the drop down menu top right
In both cases the println statements are displayed but not the benchmark results. Is this to be expected or have I messed up?
using DifferentialEquations, BenchmarkTools
A = rand(1000,1000); B = rand(1000,1000); C = rand(1000,1000)
println("TX 1 and 2")
test(A,B,C) = A + B + C
#benchmark test(A,B,C)
println("T 1 End")
t(A,B,C) = A .+ B .+ C
#benchmark t(A,B,C)
println("TX 2 End")
readline()
println("After read")
I found a workaround : remove or comment out the #benchmark from the file and
run them directly in the REPL.
This should depend on which setting you have for result type (Julia > Execution: Result Type in the Settings GUI or julia.execution.resultType in settings.json).
With "inline" result type I get:
Hovering over the BenchmarkTools.Trial box, I get:
Note the println line just shows a tick as it has been executed but didn't return anything, instead it printed to the REPL, the terminal at the bottom now looks like this:

auto-save-visited-interval not save automatically

I enabled the auto-save-visited-mode in global scope and write such a script
~/D/O/ORG/pySrc [undefined] λ cat sicp.py
#!/usr/bin/env python
def remainder(x, y):
return x % y
def gcd(a, b):
if b == 0:
retunr a
else:
return gcd(b, remainder(a, b))
print(gcd(30, 15))
Run it but find typo-error of retunr, and corrected it immediately.
The auto-save-visited-interval set as default 5, so I count to 10 and run it again
get error
File "sicp.py", line 9
retunr a
^
SyntaxError: invalid syntax
the file was not saved automatically.
Consult with auto save file, which state that files will be saved in place.
What's the problem with my usage?
doom-emacs issue
To enable a minor mode you must call its function: (auto-save-visited-mode +1). Setting the auto-save-visited-mode variable is not enough.
Try adding this to your config.el:
(auto-save-visited-mode +1)

import user defined modules into pydev

I am a beginner to Eclipse neon + Pydev combo.
Trying to use python modules I created into other modules I will be creating.
For a start, I was going to use TKinter tutorial program outlined here:
http://effbot.org/tkinterbook/tkinter-hello-again.htm
In addition to printing a statement in response to a mouse click, I want to run a small module, fibo.py
Here's my code:
import the library
from tkinter import *
import fibo
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(
frame, text="QUIT", fg="red", command=frame.quit
)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello",command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
fib(100)
print ("hi there, everyone!")
root = Tk()
app = App(root)
root.mainloop()
root.destroy() # optional; see description below
Here's fibo.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print (b, end=" ")
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Both modules are in the same project and workspace.
The editor says,"unresolved import fibo"
Why is the module fibo not recognized by in pydev/eclipse?
My ultimate goal is to run a module upon button click. If there's a more direct way to accomplish this, I would like to know.
Ok, so, based on your screenshot, the structure you have is actually:
/project (this is the PYTHONPATH root and marked as source folder)
/project/root
/project/root/__init__.py
/project/root/nested
/project/root/nested/__init__.py
/project/root/nested/example.py
/project/root/nested/fibo.py
In this case, your import should be: from root.nested import fibo. Your code may work in the command line, but that's because you added an entry to sys.path only in runtime (so, PyDev can't follow that).
The other option would be moving both example.py and fibo.py to /project.
You can also use a relative import as from . import fibo, but then, to run the module as a __main__ module, you'll have to run modules by the module name (with the -m flag) -- you can configure PyDev to do that at the preferences > PyDev > Run > Launch modules with "python -m mod.name".
As a note, if you just write:
fibo in your case, and wait for the undefined variable error to be shown, you can use Ctrl+1 in that same line to get a suggestion which will write the import for you (or you can do a code-completion which will also write an import for you automatically).

Deploy an matlab file to executable

I want to deploy an m file into an executable. I am using mcc command: mcc -m epidemic.m. Epidemic is my function which takes no arguments and returns a vector and write that vector to txt. Mcc creates epidemic.exe and when I am running that exe it creates the txt file however it seems that it doesnt return values (the return value of .exe). I am trying to run the exe from matlab using:
cmd = ['epidemic.exe '];
system(cmd);
It return cmdout " and status 0. How can I take the returned values of the .exe?
When you compile matlab code like:
function [out1, out2] = epidemic(in1, in2, in3)
%[
...
%]
to standalone (mcc -m epidemeic.m), Matlab produces somehow the following pseudo c-code and compiles it to .exe:
int main(int argc, char** argv)
{
// Load compiled code produced by mcc
HMCRInstance* hInst = loadByteCodeProducedByMccFromResources();
// Similar to have wrote in matlab "epidemic(argv[0], argv[1], ...)"
// 1) Without asking for any argument output
// 2) Argument inputs are passed as strings
int errorCode = mclFevalFromExeArg(hInst, "epidemic", argc, argv);
return errorCode; // only indicates if call to 'mclFEvalFromExeArg'
// succeded, it does not relate to out1, out2 at all.
}
NB: If you want to see the exact code produced by mcc, use mcc -W main -T codegen epidemic.m
So, directly compiling to standalone, you cannot work with outputs of your Matlab function. If you need to play around with output arguments of epidemic, either
[Simple solution] Consider saving outputs to files or display them to shell console using disp (NB: you can use isdeployed in your .m file to check if you're running from matlab or from compiled code).
[Advanced solution] Consider compiling your code to shared library (mcc -l epidemic.m) instead of standalone (mcc -m epidemeic.m)
NB: When you compile your code to shared library, mcc will produce a dll that exports the following function:
extern LIB_epidemeic_C_API
bool MW_CALL_CONV mlxEpidemic(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
nrhs/prhs are the number of input arguments and their values (as mxArray type). And nlhs/plhs are the ouput arguments you want to have when calling epidemic. Up to you to do the marshaling between mxArray and equivalent C native type.
EDIT
As you indicate that epidemic returns a vector of values, you can display them from standalone like this:
function [output] = epidemic(v1, v2, v3)
%[
% When called from system cmd line, v1, v2, v3 are passed
% as string. Here is how to convert them to expected type if required
if (ischar(v1)), v1 = str2double(v1); end
if (ischar(v2), v2 = str2double(v2); end
if (ischar(v3)), v3 = str2double(v3); end
...
output = ...;
...
if (isdeployed())
disp(output);
end
%]
An exe does not have a return value, you need to find another way to transport the data back, for example via console outputs or text files. What you get is the error code and error message.

`localfunctions` inside a package

localfunctions returns function handles to all the local functions in an m-file. However, this doesn't work in a package. For example, the following code saved as 'a.m' runs fine:
function fs = a()
fs = localfunctions;
end
function babo()
end
function hidden()
end
Called from MATLAB console:
>> a()
ans =
#babo
#hidden
But when it is inside a package as '+aaa/b.m', I get nothing:
>> aaa.b()
ans =
{}
I don't think this behavior is well documented. How do I overcome this?
I need to use localfunctions to unit test some functions within the package and I don't want to keep it outside of the package just because of this.
One solution would be to import the package before calling localfunctions:
+mypkg/mytest.m
function f = mytest()
import mypkg.*
f = localfunctions;
end
function foo()
end
function bar()
end
When called:
>> f = mypkg.mytest()
f =
#foo
#bar
>> functions(f{1})
ans =
function: 'foo'
type: 'scopedfunction'
file: 'C:\Users\Amro\Desktop\+mypkg\mytest.m'
parentage: {'foo' 'mytest'}
There is a bug in R2013b and R2014a where localfunctions does not respect the package of the file containing the local functions. This bug has been reported to The MathWorks for fixing in a future release.
Until then, Amro's workaround is the best option.
EDIT: This has been fixed in release R2014b.