These tests will verify that IPython is working correctly within Org mode.
!pip install ipythonFirst, let’s check our Python environment and ensure IPython is available:
import sys
print(f"Python version: {sys.version}")
# Check if IPython is available
try:
import IPython
print(f"IPython version: {IPython.__version__}")
print(f"IPython is correctly loaded: {'IPython' in sys.modules}")
# Get the current IPython instance
ipython = IPython.get_ipython()
if ipython:
print(f"Active IPython type: {type(ipython).__name__}")
else:
print("No active IPython instance found.")
except ImportError:
print("IPython is not installed in this environment.")Let’s define a variable and verify it persists between code blocks:
test_variable = "This variable should persist between code blocks"
print(f"Defined: {test_variable}")Now let’s check if the variable is still accessible:
try:
print(f"Retrieved: {test_variable}")
except NameError:
print("ERROR: The variable was not persisted between code blocks!")Test that IPython magic commands work:
!echo "Running a system command"%pylab --no-import-all
%config InlineBackend.figure_format = 'svg'%time sum(range(1000000))print("\nAvailable magic commands:")
%lsmagicTest help and documentation features:
# This block doesn't require you to press tab, but verifies
# that IPython's rich help is working
help(str.split)
# Print docstring
print("\nDocstring for max function:")
print(max.__doc__)
Test debugger integration:
def function_to_debug(n):
"""A function with steps we can debug"""
result = 0
for i in range(n):
result += i * i
# Uncomment to debug interactively
# import pdb; pdb.set_trace()
return result
# Run the function without debugging
result = function_to_debug(5)
print(f"Result: {result}")
# How to use the debugger
print("\nTo debug: uncomment the pdb line and re-run")
print("Common pdb commands:")
print(" n - next line")
print(" s - step into function")
print(" c - continue execution")
print(" p <expr> - print expression")
print(" q - quit debugging")Test error traceback formatting:
try:
# This will cause an error
1/0
except Exception as e:
print(f"Caught exception: {type(e).__name__}: {e}")
# Print traceback
import traceback
print("\nTraceback:")
traceback.print_exc()Test matplotlib integration:
import matplotlib.pyplot as plt
import numpy as np
# Create a simple plot
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)')
plt.title('Test Plot')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
# Save the figure to view it in Org mode
plt.savefig('test_plot.png')
print("Plot saved to test_plot.png")Test Poetry environment integration:
# Try to import poetry
try:
import poetry
print(f"Poetry is available: {poetry.__version__}")
except ImportError:
print("Poetry module not directly importable (this is normal)")
# Check if we're in a virtual environment
import os
print(f"Using virtual environment: {'VIRTUAL_ENV' in os.environ}")
if 'VIRTUAL_ENV' in os.environ:
print(f"Virtual env path: {os.environ['VIRTUAL_ENV']}")
# List installed packages
print("\nInstalled packages:")
!pip list | grep -E "ipython|numpy|matplotlib"Check memory usage:
# Try using memory_profiler if available
try:
import memory_profiler
print("Memory profiler available")
# Define a function to profile
@memory_profiler.profile
def memory_test():
"""Test memory usage"""
# Create a large list
large_list = [i for i in range(1000000)]
return sum(large_list)
# Run the function
result = memory_test()
print(f"Result: {result}")
except ImportError:
print("Memory profiler not available, install with: pip install memory_profiler")
# Alternative memory usage check
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
print(f"Memory usage: {usage.ru_maxrss / 1024:.2f} MB")Test timing functions:
import time
# Define a function to time
def time_test(n):
"""Test function for timing"""
start = time.time()
result = sum(i * i for i in range(n))
end = time.time()
return result, end - start
# Run with different inputs
for n in [10000, 100000, 1000000]:
result, duration = time_test(n)
print(f"n={n}: result={result}, time={duration:.6f} seconds")
# Use IPython's timing magic
print("\nUsing %timeit:")
%timeit sum(i * i for i in range(10000))Let’s create a function and then modify it:
def calculate(x, y):
"""Initial version of the function"""
return x + y
print(f"Initial result: calculate(5, 3) = {calculate(5, 3)}")Now modify the function and re-evaluate:
# Modified version of the function
def calculate(x, y):
"""Modified version of the function"""
return x * y
print(f"Modified result: calculate(5, 3) = {calculate(5, 3)}")Test object inspection features:
import inspect
# Create a class to inspect
class TestClass:
"""A test class for inspection"""
def __init__(self, value):
self.value = value
def double(self):
"""Return twice the value"""
return self.value * 2
def square(self):
"""Return the square of the value"""
return self.value ** 2
# Create an instance
obj = TestClass(5)
# Get source code
print("Source code:")
print(inspect.getsource(TestClass))
# Get method list
print("\nMethods:")
for name, method in inspect.getmembers(obj, predicate=inspect.ismethod):
print(f" {name}: {method.__doc__}")
# Get attributes
print("\nAttributes:")
for name, value in inspect.getmembers(obj):
if not name.startswith('_') and not inspect.ismethod(value):
print(f" {name}: {value}")Tools for diagnosing environment issues:
import sys
import os
# Python paths
print("Python path:")
for path in sys.path:
print(f" {path}")
# Environment variables
print("\nKey environment variables:")
for var in ['PYTHONPATH', 'VIRTUAL_ENV', 'PATH']:
if var in os.environ:
print(f" {var}: {os.environ[var]}")
else:
print(f" {var}: Not set")
# Module locations
print("\nModule locations:")
for module_name in ['IPython', 'numpy', 'matplotlib']:
try:
module = __import__(module_name)
print(f" {module_name}: {module.__file__}")
except ImportError:
print(f" {module_name}: Not installed")How to reset the IPython session if needed:
# To reset the IPython session, you can use:
# %reset -f
# Or to restart the kernel:
# %kill_kernel
# %connect_info
print("To reset the session, uncomment and run either:")
print(" %reset -f (clear variables)")
print(" %kill_kernel followed by %connect_info (restart kernel)")This file has tested the core features of IPython integration with Org mode. If all the code blocks executed correctly, your IPython integration is working as expected.
print("Test suite completed.")
print("If you've reached this point without errors, your IPython integration is working.")