How do you embed an ipython console with exec_lines? - ipython

I'm trying to embed an ipython console into my command line application.
I have the following:
import IPython
from traitlets.config import Config
c = Config()
c.InteractiveShellApp.exec_lines = [
'import matplotlib.pyplot as plt',
'%matplotlib',
]
return IPython.start_ipython(config=c, user_ns=globals())
However, it seems to completely ignore the "exec_lines" part since plt is not available.

See: Can you specify a command to run after you embed into IPython?
IPython.start_ipython(config=c, user_ns=locals())

Related

how to pytest an app that can use ipython embed as arg parameter?

I have a python application that has an option "-y" to end its procedure in a ipython terminal with all objects created ready for an interactive manipulation.
I'm trying to think in how can I design a pytest that could allow me, somehow, to interact with this terminal, to check if objects are there in a python session, exit, and then capture the results for assert (I know how to use capsys for example).
During my attempts (all failed so far) I got a suggestion to use pytest -s option which, obviously, is not my case.
So I have this example:
go_to_python.py
import argparse
import random
parser = argparse.ArgumentParser()
parser.add_argument(
"-y",
"--ipython",
action="store_true",
dest="ipython",
help="start iPython interpreter")
args = parser.parse_args()
if __name__ == "__main__":
randomlist = []
for i in range(0, 5):
n = random.randint(1, 30)
randomlist.append(n)
if args.ipython:
import IPython
IPython.embed(colors="neutral")
How could I create a test that could assert that randomlist is inside the ipython session?

FreeCAD CMD color lost after import

Whenenver I try to import a model via FreeCADCmd Script the objects loose all color information.
This can be checked within the GUI by running macros
import FreeCAD
import ImportGui
doc = FreeCAD.newDocument()
FreeCAD.setActiveDocument(doc.Name)
ImportGui.insert("file1.stp", doc.Name)
will preserve the colors -- but can not be run on commandline, because of ImportGui.
import FreeCAD
import Import
doc = FreeCAD.newDocument()
FreeCAD.setActiveDocument(doc.Name)
Import.insert("file1.stp", doc.Name)
will import the model without any color information.
Is there any way to import a step file into FreeCADCmd (commandline -- so no GUI) without the color information being dropped?
Or does anyone know a way to run FreeCAD (GUI Version) without running a xserver?

How to import .py in google Colaboratory?

I want to simplify code. so i make a utils.py , but Google Colaboratory directory is "/content" I read other questions. but this is not my solution
In Google's Colab notebook, How do I call a function from a Python file?
%%writefile example.py
def f():
print 'This is a function defined in a Python source file.'
# Bring the file into the local Python environment.
execfile('example.py')
f()
This is a function defined in a Python source file.
It look likes just using def().
using this, i always write the code in cell.
but i want to this code
import example.py
example.f()
A sample maybe you want:
!wget https://raw.githubusercontent.com/tensorflow/models/master/samples/core/get_started/iris_data.py -P local_modules -nc
import sys
sys.path.append('local_modules')
import iris_data
iris_data.load_data()
I have also had this problem recently.
I addressed the issue by the following steps, though it's not a perfect solution.
src = list(files.upload().values())[0]
open('util.py','wb').write(src)
import util
This code should work with Python 3:
from google.colab import drive
import importlib.util
# Mount your drive. It will be at this path: "/content/gdrive/My Drive/"
drive.mount('/content/gdrive')
# Load your module
spec = importlib.util.spec_from_file_location("YOUR_MODULE_NAME", "/content/gdrive/My Drive/utils.py")
your_module_name = importlib.util.module_from_spec(spec)
spec.loader.exec_module(your_module_name)
import importlib.util
import sys
from google.colab import drive
drive.mount('/content/gdrive')
# To add a directory with your code into a list of directories
# which will be searched for packages
sys.path.append('/content/gdrive/My Drive/Colab Notebooks')
import example.py
This works for me.
Use this if you are out of content folder! hope this help!
import sys
sys.path.insert(0,'/content/my_project')
from example import*
STEP 1. I have just created a folder 'common_module' like shown in the image :
STEP 2 called the required Class from my "colab" code cell,
sys.path.append('/content/common_module/')
from DataPreProcessHelper import DataPreProcessHelper as DPPHelper
My class file 'DataPreProcessHelper.py' looks like this
Add path of 'sample.py' file to system paths as:
import sys
sys.path.append('drive/codes/')
import sample

Ipython notebook does not print all output in a code

I have two problem in ipython juypter
1) I want ipython to print all the output without without typing print. Ipython usually prints only the last result
2) I am using python interface of Madagascar package , ( geophysical software) but when I use it in ipython notebook I don't any output.
import m8r
import urllib
#Retrieve
m8r.Fetch('french','french.asc')
fren='french.asc'
french=m8r.dd(form='native').transp().scale(dscale=2)[fren]
french.grey(color='j',allpos='y',bias=1000,scalebar='n',barlabel='Depth',barunit='m',screenratio=1,title='French model').image()
nx = 161
dx = 51.325
nz = 401
dz = 10.265
nxx= 10*(nx-1)+1
dxx= dx/10
dscal = 10/dx
refl=m8r.window(n1=1,f1=30).remap1(n1=nxx,o1=0,d1=dxx)[french]
rdip=m8r.deriv(none="0").scale(dscale=dscal)[refl]
slice =m8r.window(n1=1,f1=30).remap1(n1=nx,o1=0,d1=dx).unif2(n1=nz,d1=dz,v00='1,2')[french]
slice.grey(color='j',allpos='y',bias=1,title='2-D slice',label1='Depth',unit1='m',screenratio=0.5,screenht=6).image()
this code works in sage notebook. when I run it in sage I get graphs but this does not happed in ipython notebook

IPython Notebook: Open/select file with GUI (Qt Dialog)

When you perform the same analysis in a notebook on different data files, may be handy to graphically select a data file.
In my python scripts I usually implement a QT dialog that returns the file-name of the selected file:
from PySide import QtCore, QtGui
def gui_fname(dir=None):
"""Select a file via a dialog and return the file name.
"""
if dir is None: dir ='./'
fname = QtGui.QFileDialog.getOpenFileName(None, "Select data file...",
dir, filter="All files (*);; SM Files (*.sm)")
return fname[0]
However, running this function from an notebook
full_fname = gui_fname()
causes the kernel to die (and restart):
Interestingly, puttying this 3 command in 3 separate cells works
%matplotlib qt
full_fname = gui_fname()
%matplotlib inline
but when I put those commands in one single cell the kernel dies again.
This prevents to create a function like gui_fname_ipynb() that transparently allows selecting a file with a GUI.
For convenience, I created a notebook illustrating the problem:
Open/select file with GUI (Qt Dialog)
Any suggestion on how to execute a dialog for file selection from within an IPython Notebook?
Using Anaconda 5.0.0 on windows (Python 3.6.2, IPython 6.1.0), the following two options are both working for me.
OPTION 1: Entirely in a Jupyter notebook:
CELL 1:
%gui qt
from PyQt5.QtWidgets import QFileDialog
def gui_fname(dir=None):
"""Select a file via a dialog and return the file name."""
if dir is None: dir ='./'
fname = QFileDialog.getOpenFileName(None, "Select data file...",
dir, filter="All files (*);; SM Files (*.sm)")
return fname[0]
CELL 2:
gui_fname()
This is working for me but it seems a bit...fragile. If I combine these two things into the same cell, it crashes. Or if I omit the %gui qt, it crashes. If I "restart kernel and run all cells", it doesn't work. So I kinda like this other option...
MORE RELIABLE OPTION: Separate script that opens dialog box in a new process
(Based on mkrog code here.)
PUT THE FOLLOWING IN A SEPARATE PYTHON SCRIPT CALLED blah.py:
from sys import executable, argv
from subprocess import check_output
from PyQt5.QtWidgets import QFileDialog, QApplication
def gui_fname(directory='./'):
"""Open a file dialog, starting in the given directory, and return
the chosen filename"""
# run this exact file in a separate process, and grab the result
file = check_output([executable, __file__, directory])
return file.strip()
if __name__ == "__main__":
directory = argv[1]
app = QApplication([directory])
fname = QFileDialog.getOpenFileName(None, "Select a file...",
directory, filter="All files (*)")
print(fname[0])
...AND IN YOUR JUPYTER NOTEBOOK
import blah
blah.gui_fname()
I have a universal code where it does its job without any problem. Here is my sugestion:
try:
from tkinter import Tk
from tkFileDialog import askopenfilenames
except:
from tkinter import Tk
from tkinter import filedialog
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filenames = filedialog.askopenfilenames() # show an "Open" dialog box and return the path to the selected file
print (filenames)
hope it can be useful
This behaviour was a bug in IPython:
https://github.com/ipython/ipython/issues/4997
that was fixed here:
https://github.com/ipython/ipython/pull/5077
The function to open a gui dialog should work on current master and on the oncoming 2.0 release.
To date, the last 1.x version (1.2.1) does not include a backport of the fix.
EDIT: The example code still crashes IPython 2.x, see this issue.