diff options
Diffstat (limited to 'Examples/python')
53 files changed, 810 insertions, 202 deletions
diff --git a/Examples/python/check.list b/Examples/python/check.list index a43a5fca0..0798b5f7e 100644 --- a/Examples/python/check.list +++ b/Examples/python/check.list @@ -4,6 +4,7 @@ class constants contract docstrings +doxygen enum exception exceptproxy @@ -14,7 +15,6 @@ functor import import_template import_packages -java #libffi multimap operator diff --git a/Examples/python/doxygen/Makefile b/Examples/python/doxygen/Makefile new file mode 100644 index 000000000..1a0e3d7c5 --- /dev/null +++ b/Examples/python/doxygen/Makefile @@ -0,0 +1,27 @@ +TOP = ../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +CXXSRCS = example.cxx +TARGET = example +INTERFACE = example.i +LIBS = -lm +SWIGOPT = -doxygen + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' \ + TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp + +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' \ + TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean + rm -f example.html diff --git a/Examples/python/doxygen/example.cxx b/Examples/python/doxygen/example.cxx new file mode 100644 index 000000000..ccdb87dfe --- /dev/null +++ b/Examples/python/doxygen/example.cxx @@ -0,0 +1,48 @@ +/* File : example.cxx */ + +#include "example.h" +#define M_PI 3.14159265358979323846 + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +Circle::Circle(double r) : radius(r) { + NumCircles++; +} + +double Circle::area() { + return M_PI*radius*radius; +} + +double Circle::perimeter() { + return 2*M_PI*radius; +} + +Square::Square(double w) : width(w) { + NumSquares++; +} + +double Square::area() { + return width*width; +} + +double Square::perimeter() { + return 4*width; +} + +int NumSquares = 0; +int NumCircles = 0; + +Square MakeSquare(double r) { + return Square(r); +} + +Circle MakeCircle(double w) { + return Circle(w); +} + diff --git a/Examples/python/doxygen/example.dsp b/Examples/python/doxygen/example.dsp new file mode 100644 index 000000000..95ad8f173 --- /dev/null +++ b/Examples/python/doxygen/example.dsp @@ -0,0 +1,152 @@ +# Microsoft Developer Studio Project File - Name="example" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=example - Win32 Release
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "example.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "example.mak" CFG="example - Win32 Release"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "example - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "example - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "example - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Debug"
+# PROP Intermediate_Dir "Debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "$(PYTHON_INCLUDE)" /D "SWIG_PYTHON_INTERPRETER_NO_DEBUG" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /GZ /c
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "_DEBUG"
+# ADD RSC /l 0x809 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /debug /machine:I386 /out:"_example.pyd" /pdbtype:sept
+
+!ELSEIF "$(CFG)" == "example - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Release"
+# PROP Intermediate_Dir "Release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "$(PYTHON_INCLUDE)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "EXAMPLE_EXPORTS" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x809 /d "NDEBUG"
+# ADD RSC /l 0x809 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib "$(PYTHON_LIB)" /nologo /dll /machine:I386 /out:"_example.pyd"
+
+!ENDIF
+
+# Begin Target
+
+# Name "example - Win32 Debug"
+# Name "example - Win32 Release"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=.\example.cxx
+# End Source File
+# Begin Source File
+
+SOURCE=.\example_wrap.cxx
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# Begin Source File
+
+SOURCE=.\example.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# Begin Source File
+
+SOURCE=.\example.i
+
+!IF "$(CFG)" == "example - Win32 Debug"
+
+# Begin Custom Build
+InputPath=.\example.i
+InputName=example
+
+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+ echo In order to function correctly, please ensure the following environment variables are correctly set:
+ echo PYTHON_INCLUDE: %PYTHON_INCLUDE%
+ echo PYTHON_LIB: %PYTHON_LIB%
+ echo on
+ ..\..\..\swig.exe -c++ -python "$(InputPath)"
+
+# End Custom Build
+
+!ELSEIF "$(CFG)" == "example - Win32 Release"
+
+# Begin Custom Build
+InputPath=.\example.i
+InputName=example
+
+"$(InputName)_wrap.cxx" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+ echo In order to function correctly, please ensure the following environment variables are correctly set:
+ echo PYTHON_INCLUDE: %PYTHON_INCLUDE%
+ echo PYTHON_LIB: %PYTHON_LIB%
+ echo on
+ ..\..\..\swig.exe -c++ -python "$(InputPath)"
+
+# End Custom Build
+
+!ENDIF
+
+# End Source File
+# End Target
+# End Project
diff --git a/Examples/python/doxygen/example.h b/Examples/python/doxygen/example.h new file mode 100644 index 000000000..203348ae4 --- /dev/null +++ b/Examples/python/doxygen/example.h @@ -0,0 +1,107 @@ +/*! \file example.h +This file provides a simple set of Shape classes. */ + +/*! Base class for all shapes. + \author Bob + */ +class Shape { +public: + /*! Default constructor for creating a Shape */ + Shape() { + nshapes++; + } + /*! Destructor for destroying a Shape */ + virtual ~Shape() { + nshapes--; + } + double x; /*!< x co-ordinate */ + double y; /*!< y co-ordinate */ + void move(double dx, double dy); /*!< Move a shape to a new co-ordinate + \param dx x co-ordinate + \param dy y co-ordinate */ + virtual double area() = 0; /*!< \return the area */ + virtual double perimeter() = 0; /*!< \return the perimeter */ + static int nshapes; /*!< Number of shapes currently in existence */ +}; + +/*! A class for representing a circle. + \author Jack + */ +class Circle : public Shape { +private: + double radius; +public: + /*! Construct a circle + * \param r radius of the circle */ + Circle(double r); + /*! Calculate the area of the circle + * \return calculated area */ + virtual double area(); + /*! Calculate the perimeter of the circle + * \return calculated perimeter of the circle */ + virtual double perimeter(); +}; + +/// A class for representing a square. +class Square : public Shape { +private: + double width; +public: + /** Construct a square + * \param w width of the square */ + Square(double w); + /** Calculate the area of the square + * \return calculated area */ + virtual double area(); + /** Calculate the perimeter of the square + * \return calculated perimeter of the square */ + virtual double perimeter(); +}; + +/// A class for representing a rectangle, templated on the type for the rectangle dimensions +template<typename T> +class Rectangle : public Shape { +private: + T height; + T width; +public: + /** Construct a rectangle + * \param h height of the rectangle + * \param w width of the rectangle */ + Rectangle(T h, T w) : height(h), width(w) {} + /** Calculate the area of the rectangle + * \return calculated area */ + virtual double area() { return width*height; } + /** Calculate the perimeter of the rectangle + * \return calculated perimeter of the rectangle */ + virtual double perimeter() { return 2*height + 2*width; } +}; + + +/*! Factory function for creating a square + * \param r width of the square + * \return a fully constructed square */ +Square MakeSquare(double r); + +/*! Factory function for creating a circle + * \param w radius of the circle + * \return a fully constructed circle */ +Circle MakeCircle(double w); + +/*! Factory function for creating a rectangle + * \param h height of the rectangle + * \param w width of the rectangle + * \return a fully constructed rectangle */ +template<typename T> +Rectangle<T> MakeRectangle(T h, T w) { + return Rectangle<T>(h, w); +} + + + +/*! Total number of circles ever created */ +extern int NumCircles; + +/// Total number of squares ever created +extern int NumSquares; + diff --git a/Examples/python/doxygen/example.i b/Examples/python/doxygen/example.i new file mode 100644 index 000000000..803563dd9 --- /dev/null +++ b/Examples/python/doxygen/example.i @@ -0,0 +1,17 @@ +%module example + +%{ +#include "example.h" +%} + +%immutable NumSquares; +%immutable NumCircles; + +%include "example.h" + +/*! - this instantiation uses type int */ +%template(RectangleInt) Rectangle<int>; + +/*! - this instantiation uses type int */ +%template(MakeRectangleInt) MakeRectangle<int>; + diff --git a/Examples/python/doxygen/runme.py b/Examples/python/doxygen/runme.py new file mode 100644 index 000000000..e23528874 --- /dev/null +++ b/Examples/python/doxygen/runme.py @@ -0,0 +1,28 @@ +# This example shows simple usage of the wrapped Shape classes. +# The main purpose of this example is to show the doxygen comments translation to PyDoc comments. +# Users should look at the generated example.py file. +# The generated PyDoc can be viewed in a browser by opening the example.html file. + +import example + +print "Creating some objects:" +c = example.MakeCircle(10) +print " Created circle", c +s = example.MakeSquare(10) +print " Created square", s +r = example.MakeRectangleInt(10, 20) +print " Created rectangle", r + +print "\nHere are some properties of the shapes:" +for o in [c, s, r]: + print " ", o + print " area = ", o.area() + print " perimeter = ", o.perimeter() + +print "\nRunning pydoc, this is the equivalent to executing: pydoc -w ./example.py" + +import pydoc + +pydoc.writedoc("example") + +print "Open example.html in your browser to view the generated python docs" diff --git a/Examples/python/exception/example.h b/Examples/python/exception/example.h index 8f9a977b0..bc744cda7 100644 --- a/Examples/python/exception/example.h +++ b/Examples/python/exception/example.h @@ -1,6 +1,6 @@ /* File : example.h */ -#include <string> +#include <string.h> #ifndef SWIG struct A { }; @@ -16,30 +16,26 @@ public: char msg[256]; }; -#if defined(_MSC_VER) - #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) -#endif - class Test { public: - int simple() throw(int) { + int simple() { throw(37); return 1; } - int message() throw(const char *) { + int message() { throw("I died."); return 1; } - int hosed() throw(Exc) { + int hosed() { throw(Exc(42,"Hosed")); return 1; } - int unknown() throw(A*) { + int unknown() { static A a; throw &a; return 1; } - int multi(int x) throw(int, const char *, Exc) { + int multi(int x) { if (x == 1) throw(37); if (x == 2) throw("Bleah!"); if (x == 3) throw(Exc(42,"No-go-diggy-die")); @@ -47,7 +43,3 @@ public: } }; -#if defined(_MSC_VER) - #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) -#endif - diff --git a/Examples/python/exception/example.i b/Examples/python/exception/example.i index 817c5221c..3a3a6548f 100644 --- a/Examples/python/exception/example.i +++ b/Examples/python/exception/example.i @@ -7,6 +7,12 @@ %include "std_string.i" +%catches(int) Test::simple(); +%catches(const char *) Test::message(); +%catches(Exc) Test::hosed(); +%catches(A*) Test::unknown(); +%catches(int, const char *, Exc) Test::multi(int x); + /* Let's just grab the original header file here */ %include "example.h" diff --git a/Examples/python/exceptproxy/example.h b/Examples/python/exceptproxy/example.h index ec7107a5e..3ee6d765d 100644 --- a/Examples/python/exceptproxy/example.h +++ b/Examples/python/exceptproxy/example.h @@ -8,10 +8,6 @@ class FullError { FullError(int m) : maxsize(m) { } }; -#if defined(_MSC_VER) - #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) -#endif - template<typename T> class Queue { int maxsize; T *items; @@ -27,7 +23,7 @@ template<typename T> class Queue { ~Queue() { delete [] items; } - void enqueue(T x) throw(FullError) { + void enqueue(T x) { if (nitems == maxsize) { throw FullError(maxsize); } @@ -47,8 +43,3 @@ template<typename T> class Queue { } }; - -#if defined(_MSC_VER) - #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) -#endif - diff --git a/Examples/python/exceptproxy/example.i b/Examples/python/exceptproxy/example.i index 0a46afbb6..4ad960845 100644 --- a/Examples/python/exceptproxy/example.i +++ b/Examples/python/exceptproxy/example.i @@ -20,29 +20,12 @@ the header file, the enqueue method throws FullError and the dequeue method throws EmptyError. Since we don't want to define an exception handler for everything, we - simply write a handler each method individually. + simply write a handler for each method individually. Note: the *::enqueue syntax means that we simply define the handler for any class with this method defined. */ -/* - First we need to 'disable' the default swig throw mechanism for the - FullError class. We do this by rethrowing the exception. - - Note that this is necessary since the class appears in a throw - declaration: - - - void enqueue(T x) throw(FullError); - - hence, swig recognizes it as an exception class and it will generate - the necessary code to catch it and rethrow it to the python side. - -*/ -%typemap(throws) FullError "(void)$1; throw;"; - - %exception *::enqueue { try { $action @@ -76,15 +59,15 @@ */ /* - Now, the EmpytError doesn't appear in a throw declaration, and hence - we need to 'mark' it as an exception class. In python, classes that - are used as exception are 'special', and need to be wrapped as - 'classic' ones. - - This is a python issue, and if you don't mark the class, you will - see 'interesting' behaviours at the python side. - - + Python classes that are used as exceptions need to be subclasses of the + "Exception" class, and so SWIG needs to know which wrapped classes may be + used in this way. You can explicitly tell SWIG this by using + %exceptionclass. SWIG will implicitly set this feature for classes which + appear in a throw declaration, but it's not a problem to explicitly + mark such classes as well. + + This is a Python requirement - if you fail to mark such classes with + %exceptionclass you may see 'interesting' behaviour on the Python side. */ %exceptionclass EmptyError; %exceptionclass FullError; diff --git a/Examples/python/extend/runme.py b/Examples/python/extend/runme.py index 2bb38fadc..e97358b99 100644 --- a/Examples/python/extend/runme.py +++ b/Examples/python/extend/runme.py @@ -18,7 +18,7 @@ class CEO(example.Manager): # Create an instance of our employee extension class, CEO. The calls to # getName() and getPosition() are standard, the call to getTitle() uses -# the director wrappers to call CEO.getPosition. e = CEO("Alice") +# the director wrappers to call CEO.getPosition. e = CEO("Alice") print e.getName(), "is a", e.getPosition() diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile index f428d6f5c..c7f9a830b 100644 --- a/Examples/python/import_packages/Makefile +++ b/Examples/python/import_packages/Makefile @@ -8,11 +8,12 @@ import_packages_subdirs = \ from_init1 \ from_init2 \ from_init3 \ + module_is_init \ relativeimport1 \ relativeimport2 \ relativeimport3 \ split_modules \ - namespace_pkg + namespace_pkg \ check: build @@ -21,19 +22,19 @@ check: build mkdir -p `dirname $$file`; \ cp "${SRCDIR}$$file" "$$file" || exit 1; \ done; \ - fi; \ + fi for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) check); \ + (cd $$s && $(MAKE) check) || exit 1; \ done build: for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build) || exit 1; \ done static: for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static) || exit 1; \ done clean: @@ -42,7 +43,7 @@ clean: for file in `cd $(SRCDIR) && find . -type f -name "*.py"`; do \ rm -f "$$file" || exit 1; \ done; \ - fi; \ + fi for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) clean); \ + (cd $$s && $(MAKE) clean) || exit 1; \ done diff --git a/Examples/python/import_packages/from_init1/runme.py b/Examples/python/import_packages/from_init1/runme.py index dda397487..a663a136b 100644 --- a/Examples/python/import_packages/from_init1/runme.py +++ b/Examples/python/import_packages/from_init1/runme.py @@ -1,13 +1,35 @@ -import sys import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +if sys.version_info < (2, 5): + print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + sys.exit(0) + if sys.version_info < (3, 0): import py2.pkg2 print " Finished importing py2.pkg2" + commandline = sys.executable + " -m py2.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py2.pkg2.foo" + run_except_on_windows(commandline) else: import py3.pkg2 print " Finished importing py3.pkg2" + # commandline = sys.executable + " -m py3.pkg2.bar" + # run_except_on_windows(commandline) + # commandline = sys.executable + " -m py3.pkg2.foo" + # run_except_on_windows(commandline) + +# TODO: Commented out code above results in (from python-3.6 onwards): +# RuntimeWarning: 'py3.pkg2.bar' found in sys.modules after import of package 'py3.pkg2', but prior to execution of 'py3.pkg2.bar'; this may result in unpredictable behaviour diff --git a/Examples/python/import_packages/from_init2/runme.py b/Examples/python/import_packages/from_init2/runme.py index dda397487..3c7b12693 100644 --- a/Examples/python/import_packages/from_init2/runme.py +++ b/Examples/python/import_packages/from_init2/runme.py @@ -1,13 +1,31 @@ -import sys import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +if sys.version_info < (2, 5): + print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + sys.exit(0) + if sys.version_info < (3, 0): import py2.pkg2 print " Finished importing py2.pkg2" + commandline = sys.executable + " -m py2.pkg2.bar" + run_except_on_windows(commandline) else: import py3.pkg2 print " Finished importing py3.pkg2" + # commandline = sys.executable + " -m py3.pkg2.bar" + # run_except_on_windows(commandline) + +# TODO: Commented out code above results in (from python-3.6 onwards): +# RuntimeWarning: 'py3.pkg2.bar' found in sys.modules after import of package 'py3.pkg2', but prior to execution of 'py3.pkg2.bar'; this may result in unpredictable behaviour diff --git a/Examples/python/import_packages/from_init3/runme.py b/Examples/python/import_packages/from_init3/runme.py index dda397487..3c7b12693 100644 --- a/Examples/python/import_packages/from_init3/runme.py +++ b/Examples/python/import_packages/from_init3/runme.py @@ -1,13 +1,31 @@ -import sys import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +if sys.version_info < (2, 5): + print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + sys.exit(0) + if sys.version_info < (3, 0): import py2.pkg2 print " Finished importing py2.pkg2" + commandline = sys.executable + " -m py2.pkg2.bar" + run_except_on_windows(commandline) else: import py3.pkg2 print " Finished importing py3.pkg2" + # commandline = sys.executable + " -m py3.pkg2.bar" + # run_except_on_windows(commandline) + +# TODO: Commented out code above results in (from python-3.6 onwards): +# RuntimeWarning: 'py3.pkg2.bar' found in sys.modules after import of package 'py3.pkg2', but prior to execution of 'py3.pkg2.bar'; this may result in unpredictable behaviour diff --git a/Examples/python/import_packages/module_is_init/Makefile b/Examples/python/import_packages/module_is_init/Makefile new file mode 100644 index 000000000..43763aa4b --- /dev/null +++ b/Examples/python/import_packages/module_is_init/Makefile @@ -0,0 +1,15 @@ +TOP = ../../.. +LIBS = + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run + +build: + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build + +static: + cd pkg1 && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + cd pkg1 && $(MAKE) clean diff --git a/Examples/python/import_packages/module_is_init/README b/Examples/python/import_packages/module_is_init/README new file mode 100644 index 000000000..ee7391cda --- /dev/null +++ b/Examples/python/import_packages/module_is_init/README @@ -0,0 +1,18 @@ +This example tests renaming the generated SWIG pure Python module to __init__.py +to turn the module into a Python package. + +Use 'python runme.py' to run the test. + +Overview: +--------- + +SWIG generates a pure Python module foo.py from the input interface file foo.i. +The foo.py file is generated within the pkg1 directory and is then renamed __init__.py. +This results in everything in the SWIG generated module being available in the Python +pkg1 package. + +This approach of turning the SWIG generated module into a package worked in versions +of SWIG up to swig-3.0.8, but stopped working from swig-3.0.9 until it was +re-instated in swig-4.0.0. However, Python 2.7 or 3.3 and later are needed to +work out of the box. Python 3.2 does not work as this version of Python does +not set __package__ in __init__.py. diff --git a/Examples/python/import_packages/module_is_init/pkg1/Makefile b/Examples/python/import_packages/module_is_init/pkg1/Makefile new file mode 100644 index 000000000..d9d83ed0a --- /dev/null +++ b/Examples/python/import_packages/module_is_init/pkg1/Makefile @@ -0,0 +1,20 @@ +TOP = ../../../.. +SWIGEXE = $(TOP)/../swig +SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib +SWIGOPT = +LIBS = + +build: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp + mv foo.py __init__.py + +static: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ + SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ + SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean + rm -f __init__.py diff --git a/Examples/python/import_packages/module_is_init/pkg1/foo.hpp b/Examples/python/import_packages/module_is_init/pkg1/foo.hpp new file mode 100644 index 000000000..01c462266 --- /dev/null +++ b/Examples/python/import_packages/module_is_init/pkg1/foo.hpp @@ -0,0 +1,10 @@ + +int foofunction(int i) { + return i *= 10; +} + +struct FooClass { + int foomethod(int i) { + return i += 5; + } +}; diff --git a/Examples/python/import_packages/module_is_init/pkg1/foo.i b/Examples/python/import_packages/module_is_init/pkg1/foo.i new file mode 100644 index 000000000..f8d71380c --- /dev/null +++ b/Examples/python/import_packages/module_is_init/pkg1/foo.i @@ -0,0 +1,5 @@ +%module foo +%{ +#include "./foo.hpp" +%} +%include "./foo.hpp" diff --git a/Examples/python/import_packages/module_is_init/runme.py b/Examples/python/import_packages/module_is_init/runme.py new file mode 100644 index 000000000..b5e646e85 --- /dev/null +++ b/Examples/python/import_packages/module_is_init/runme.py @@ -0,0 +1,26 @@ +import os.path +import sys + +# Test import of a SWIG generated module renamed as the package's __init__.py +testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) +print "Testing " + testname + " - module renamed as __init__.py" + +if sys.version_info >= (3, 0, 0) and sys.version_info < (3, 3, 0): + print " Not importing as Python version is >= 3.0 and < 3.3" + # Package detection does not work in these versions. + # Can be fixed by using this in the interface file: + # %module(moduleimport="from . import $module") foo # without -builtin + # %module(moduleimport="from .$module import *") foo # with -builtin + sys.exit(0) + +import pkg1 +print " Finished importing pkg1" + +if pkg1.foofunction(123) != 1230: + raise RuntimeError("foofunction failed") + +fc = pkg1.FooClass() +if fc.foomethod(1) != 6: + raise RuntimeError("foomethod failed") + +print " Finished testing pkg1" diff --git a/Examples/python/import_packages/namespace_pkg/nonpkg.py b/Examples/python/import_packages/namespace_pkg/nonpkg.py index acf0aedbd..52be74db4 100644 --- a/Examples/python/import_packages/namespace_pkg/nonpkg.py +++ b/Examples/python/import_packages/namespace_pkg/nonpkg.py @@ -1,5 +1,22 @@ +import os +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) + +print(" Starting subtest " + os.path.basename(__file__)) + # import robin as a module in the global namespace import robin +print(" Finished importing robin") + +if not(robin.run() == "AWAY!"): + raise RuntimeError("test failed") -assert(robin.run() == "AWAY!") +commandline = sys.executable + " -m robin" +run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/namespace_pkg/normal.py b/Examples/python/import_packages/namespace_pkg/normal.py index fc26c0216..0eb8f517c 100644 --- a/Examples/python/import_packages/namespace_pkg/normal.py +++ b/Examples/python/import_packages/namespace_pkg/normal.py @@ -1,7 +1,23 @@ +import os +import subprocess import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) + +print(" Starting subtest " + os.path.basename(__file__)) + # Package brave found under one path -sys.path.insert(0, 'path1') +sys.path.insert(0, "path1") from brave import robin +print(" Finished from brave import robin") + +if not(robin.run() == "AWAY!"): + raise RuntimeError("test failed") -assert(robin.run() == "AWAY!") +commandline = sys.executable + " -m brave.robin" +run_except_on_windows(commandline, env = {"PYTHONPATH": "path1"}) diff --git a/Examples/python/import_packages/namespace_pkg/nstest.py b/Examples/python/import_packages/namespace_pkg/nstest.py index 9b075ad8c..4d618a6ad 100644 --- a/Examples/python/import_packages/namespace_pkg/nstest.py +++ b/Examples/python/import_packages/namespace_pkg/nstest.py @@ -1,11 +1,17 @@ import sys import os import shutil +import subprocess import zipfile +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) def copyMods(): - dirs = ['path1', 'path2', 'path3'] + dirs = ["path1", "path2", "path3"] # Clean out any old package paths for d in dirs: @@ -14,20 +20,20 @@ def copyMods(): for d in dirs: os.mkdir(d) - os.mkdir(os.path.join(d, 'brave')) + os.mkdir(os.path.join(d, "brave")) - shutil.copy('robin.py', os.path.join('path1', 'brave')) - os.system('cp _robin.* ' + os.path.join('path1', 'brave')) + shutil.copy("robin.py", os.path.join("path1", "brave")) + subprocess.check_call("cp _robin.* " + os.path.join("path1", "brave"), shell=True) - shutil.copy('robin.py', os.path.join('path2', 'brave')) - os.system('cp _robin.* ' + os.path.join('path3', 'brave')) + shutil.copy("robin.py", os.path.join("path2", "brave")) + subprocess.check_call("cp _robin.* " + os.path.join("path3", "brave"), shell=True) mkzip() def mkzip(): zf = zipfile.ZipFile("path4.zip", "w") - zf.writestr("brave/", b'') - zf.write('robin.py', 'brave/robin.py') + zf.writestr("brave/", b"") + zf.write("robin.py", "brave/robin.py") zf.close() @@ -35,10 +41,10 @@ def main(): copyMods() # Run each test with a separate interpreter - os.system(sys.executable + " nonpkg.py") - os.system(sys.executable + " normal.py") - os.system(sys.executable + " split.py") - os.system(sys.executable + " zipsplit.py") + run_except_on_windows(sys.executable + " nonpkg.py") + run_except_on_windows(sys.executable + " normal.py") + run_except_on_windows(sys.executable + " split.py") + run_except_on_windows(sys.executable + " zipsplit.py") if __name__ == "__main__": diff --git a/Examples/python/import_packages/namespace_pkg/runme.py b/Examples/python/import_packages/namespace_pkg/runme.py index 9c22d36fb..d2af05619 100644 --- a/Examples/python/import_packages/namespace_pkg/runme.py +++ b/Examples/python/import_packages/namespace_pkg/runme.py @@ -1,7 +1,8 @@ # These examples rely on namespace packages. Don't # run them for old python interpreters. -import sys import os.path +import subprocess +import sys testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - namespace packages" diff --git a/Examples/python/import_packages/namespace_pkg/split.py b/Examples/python/import_packages/namespace_pkg/split.py index 1b66c2d49..9d786dc07 100644 --- a/Examples/python/import_packages/namespace_pkg/split.py +++ b/Examples/python/import_packages/namespace_pkg/split.py @@ -1,9 +1,25 @@ +import os +import subprocess import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) + +print(" Starting subtest " + os.path.basename(__file__)) + # Package brave split into two paths. # path2/brave/robin.py and path3/brave/_robin.so -sys.path.insert(0, 'path2') -sys.path.insert(0, 'path3') +sys.path.insert(0, "path2") +sys.path.insert(0, "path3") from brave import robin +print(" Finished from brave import robin") + +if not(robin.run() == "AWAY!"): + raise RuntimeError("test failed") -assert(robin.run() == "AWAY!") +commandline = sys.executable + " -m brave.robin" +run_except_on_windows(commandline , env = {"PYTHONPATH": "path2:path3"}) diff --git a/Examples/python/import_packages/namespace_pkg/zipsplit.py b/Examples/python/import_packages/namespace_pkg/zipsplit.py index 9e35559e3..30434f9c0 100644 --- a/Examples/python/import_packages/namespace_pkg/zipsplit.py +++ b/Examples/python/import_packages/namespace_pkg/zipsplit.py @@ -1,9 +1,25 @@ +import os +import subprocess import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) + +print(" Starting subtest " + os.path.basename(__file__)) + # Package brave split into two paths. # brave/robin.py (in path4.zip) and path3/brave/_robin.so -sys.path.insert(0, 'path4.zip') -sys.path.insert(0, 'path3') +sys.path.insert(0, "path4.zip") +sys.path.insert(0, "path3") from brave import robin +print(" Finished from brave import robin") + +if not(robin.run() == "AWAY!"): + raise RuntimeError("test failed") -assert(robin.run() == "AWAY!") +commandline = sys.executable + " -m brave.robin" +run_except_on_windows(commandline, env = {"PYTHONPATH": "path3:path4.zip"}) diff --git a/Examples/python/import_packages/relativeimport1/runme.py b/Examples/python/import_packages/relativeimport1/runme.py index 997476b1d..87101ea46 100644 --- a/Examples/python/import_packages/relativeimport1/runme.py +++ b/Examples/python/import_packages/relativeimport1/runme.py @@ -1,13 +1,32 @@ -import sys import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) with -relativeimport" +if sys.version_info < (2, 5): + print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + sys.exit(0) + if sys.version_info < (3, 0): import py2.pkg2.bar print " Finished importing py2.pkg2.bar" + commandline = sys.executable + " -m py2.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py2.pkg2.pkg3.foo" + run_except_on_windows(commandline) else: import py3.pkg2.bar print " Finished importing py3.pkg2.bar" + commandline = sys.executable + " -m py3.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py3.pkg2.pkg3.foo" + run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/relativeimport2/runme.py b/Examples/python/import_packages/relativeimport2/runme.py index 9789afc18..f5b55782f 100644 --- a/Examples/python/import_packages/relativeimport2/runme.py +++ b/Examples/python/import_packages/relativeimport2/runme.py @@ -1,13 +1,32 @@ -import sys import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" +if sys.version_info < (2, 5): + print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + sys.exit(0) + if sys.version_info < (3, 0): import py2.pkg2.bar print " Finished importing py2.pkg2.bar" + commandline = sys.executable + " -m py2.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py2.pkg2.pkg3.pkg4.foo" + run_except_on_windows(commandline) else: import py3.pkg2.bar print " Finished importing py3.pkg2.bar" + commandline = sys.executable + " -m py3.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py3.pkg2.pkg3.pkg4.foo" + run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/relativeimport3/runme.py b/Examples/python/import_packages/relativeimport3/runme.py index 997476b1d..87101ea46 100644 --- a/Examples/python/import_packages/relativeimport3/runme.py +++ b/Examples/python/import_packages/relativeimport3/runme.py @@ -1,13 +1,32 @@ -import sys import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of modules content from within __init__.py testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) with -relativeimport" +if sys.version_info < (2, 5): + print " Skipping test as Python version is < 2.5 and does not support relative import syntax: 'from . import x'" + sys.exit(0) + if sys.version_info < (3, 0): import py2.pkg2.bar print " Finished importing py2.pkg2.bar" + commandline = sys.executable + " -m py2.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py2.pkg2.pkg3.foo" + run_except_on_windows(commandline) else: import py3.pkg2.bar print " Finished importing py3.pkg2.bar" + commandline = sys.executable + " -m py3.pkg2.bar" + run_except_on_windows(commandline) + commandline = sys.executable + " -m py3.pkg2.pkg3.foo" + run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/same_modnames1/runme.py b/Examples/python/import_packages/same_modnames1/runme.py index 3c3c00c1a..a64551bfd 100644 --- a/Examples/python/import_packages/same_modnames1/runme.py +++ b/Examples/python/import_packages/same_modnames1/runme.py @@ -1,4 +1,12 @@ import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) # Test import of same modules from different packages testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) @@ -10,10 +18,9 @@ print " Finished importing pkg2.foo" var2 = pkg2.foo.Pkg2_Foo() classname = str(type(var2)) -# Check for an old-style class if swig was run in -classic mode -if classname == "<type 'instance'>": - classname = str(var2.__class__) - if classname.find("pkg2.foo.Pkg2_Foo") == -1: raise RuntimeError("failed type checking: " + classname) print " Successfully created object pkg2.foo.Pkg2_Foo" + +commandline = sys.executable + " -m pkg2.foo" +run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/same_modnames2/runme.py b/Examples/python/import_packages/same_modnames2/runme.py index 38daad0a3..c2cf2744c 100644 --- a/Examples/python/import_packages/same_modnames2/runme.py +++ b/Examples/python/import_packages/same_modnames2/runme.py @@ -1,4 +1,12 @@ import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - %module(package=...) + python 'import' in __init__.py" @@ -9,10 +17,9 @@ print " Finished importing pkg1.pkg2.foo" var2 = pkg1.pkg2.foo.Pkg2_Foo() classname = str(type(var2)) -# Check for an old-style class if swig was run in -classic mode -if classname == "<type 'instance'>": - classname = str(var2.__class__) - if classname.find("pkg1.pkg2.foo.Pkg2_Foo") == -1: raise RuntimeError("failed type checking: " + classname) print " Successfully created object pkg1.pkg2.foo.Pkg2_Foo" + +commandline = sys.executable + " -m pkg1.pkg2.foo" +run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/split_modules/Makefile b/Examples/python/import_packages/split_modules/Makefile index 65d635bb7..9eaaabd32 100644 --- a/Examples/python/import_packages/split_modules/Makefile +++ b/Examples/python/import_packages/split_modules/Makefile @@ -6,21 +6,21 @@ subdirs = vanilla vanilla_split check: build for s in $(subdirs); do \ - (cd $$s && $(MAKE) check); \ + (cd $$s && $(MAKE) check) || exit 1; \ done build: for s in $(subdirs); do \ - (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build); \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build) || exit 1; \ done static: for s in $(subdirs); do \ - (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static); \ + (cd $$s && $(MAKE) SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static) || exit 1; \ done clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean for s in $(subdirs); do \ - (cd $$s && $(MAKE) clean); \ + (cd $$s && $(MAKE) clean) || exit 1; \ done diff --git a/Examples/python/import_packages/split_modules/README b/Examples/python/import_packages/split_modules/README index 0cb543e8a..d2ca15e7a 100644 --- a/Examples/python/import_packages/split_modules/README +++ b/Examples/python/import_packages/split_modules/README @@ -2,6 +2,9 @@ between two packages. Specifically the pure python part is part of a package and the C/C++ part is not in any package at all. Historically SWIG has supported this sort of thing. +From SWIG 4.0.0 onwards, split modules are not supported by default. +The %module directive needs to be customised with the moduleimport attribute +in order to import the a global C/C++ module. vanilla # "plane Jane" module both halves in pkg1 vanilla_split # python 1/2 in pkg1 C 1/2 in global namespace diff --git a/Examples/python/import_packages/split_modules/vanilla/runme.py b/Examples/python/import_packages/split_modules/vanilla/runme.py index a188364f1..79d79b4c3 100644 --- a/Examples/python/import_packages/split_modules/vanilla/runme.py +++ b/Examples/python/import_packages/split_modules/vanilla/runme.py @@ -1,4 +1,12 @@ import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - split modules" @@ -7,4 +15,8 @@ import pkg1.foo print " Finished importing pkg1.foo" -assert(pkg1.foo.count() == 3) +if not(pkg1.foo.count() == 3): + raise RuntimeError("test failed") + +commandline = sys.executable + " -m pkg1.foo" +run_except_on_windows(commandline) diff --git a/Examples/python/import_packages/split_modules/vanilla_split/Makefile b/Examples/python/import_packages/split_modules/vanilla_split/Makefile index c322b5aec..5d1c3521c 100644 --- a/Examples/python/import_packages/split_modules/vanilla_split/Makefile +++ b/Examples/python/import_packages/split_modules/vanilla_split/Makefile @@ -19,4 +19,6 @@ static: clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean - cd pkg1 && $(MAKE) -f $(TOP)/../Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean + if test -d pkg1; then \ + cd pkg1 && $(MAKE) -f $(TOP)/../Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean; \ + fi diff --git a/Examples/python/import_packages/split_modules/vanilla_split/foo.i b/Examples/python/import_packages/split_modules/vanilla_split/foo.i index 60ce16ec3..81ad43a5b 100644 --- a/Examples/python/import_packages/split_modules/vanilla_split/foo.i +++ b/Examples/python/import_packages/split_modules/vanilla_split/foo.i @@ -1,4 +1,9 @@ -%module(package="pkg1") foo +#if defined(SWIGPYTHON_BUILTIN) /* defined when using -builtin */ +%module(package="pkg1", moduleimport="from $module import *") foo +#else +%module(package="pkg1", moduleimport="import $module") foo +#endif + %{ static unsigned count(void) { diff --git a/Examples/python/import_packages/split_modules/vanilla_split/runme.py b/Examples/python/import_packages/split_modules/vanilla_split/runme.py index a188364f1..79d79b4c3 100644 --- a/Examples/python/import_packages/split_modules/vanilla_split/runme.py +++ b/Examples/python/import_packages/split_modules/vanilla_split/runme.py @@ -1,4 +1,12 @@ import os.path +import subprocess +import sys + +def run_except_on_windows(commandline, env=None): + if os.name != "nt" and sys.platform != "cygwin": + # Strange failures on windows/cygin/mingw + subprocess.check_call(commandline, env=env, shell=True) + print(" Finished running: " + commandline) testname = os.path.basename(os.path.dirname(os.path.abspath(__file__))) print "Testing " + testname + " - split modules" @@ -7,4 +15,8 @@ import pkg1.foo print " Finished importing pkg1.foo" -assert(pkg1.foo.count() == 3) +if not(pkg1.foo.count() == 3): + raise RuntimeError("test failed") + +commandline = sys.executable + " -m pkg1.foo" +run_except_on_windows(commandline) diff --git a/Examples/python/java/Example.java b/Examples/python/java/Example.java deleted file mode 100644 index 91ddb1ac5..000000000 --- a/Examples/python/java/Example.java +++ /dev/null @@ -1,29 +0,0 @@ -public class Example { - public int mPublicInt; - - public Example() { - mPublicInt = 0; - } - - public Example(int IntVal) { - mPublicInt = IntVal; - } - - - public int Add(int a, int b) { - return (a+b); - } - - public float Add(float a, float b) { - return (a+b); - } - - public String Add(String a, String b) { - return (a+b); - } - - public Example Add(Example a, Example b) { - return new Example(a.mPublicInt + b.mPublicInt); - } -} - diff --git a/Examples/python/java/Makefile b/Examples/python/java/Makefile deleted file mode 100644 index 7c75e6b91..000000000 --- a/Examples/python/java/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -TOP = ../.. -SWIGEXE = $(TOP)/../swig -SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib -CXXSRCS = -TARGET = example -INTERFACE = example.i -LIBS = -lm - -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run - -build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' \ - SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ - CXXSHARED="gcj -fpic -shared Example.class" DEFS='' LIBS="-lstdc++" python_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean - rm -f $(TARGET).py - rm -f *.class Example.h - -Example.class Example.h: $(SRCDIR)Example.java - gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java - gcjh Example.class diff --git a/Examples/python/java/example.i b/Examples/python/java/example.i deleted file mode 100644 index 80e08870f..000000000 --- a/Examples/python/java/example.i +++ /dev/null @@ -1,13 +0,0 @@ -%module example -%include <cni.i> - -%{ -#include "Example.h" -%} - - -%include Example.h - -%extend Example { - ~Example() {} -} diff --git a/Examples/python/java/runme.py b/Examples/python/java/runme.py deleted file mode 100644 index 641ba27dd..000000000 --- a/Examples/python/java/runme.py +++ /dev/null @@ -1,16 +0,0 @@ -from example import * - -JvCreateJavaVM(None) -JvAttachCurrentThread(None, None) - -e1 = Example(1) -e2 = Example(2) - -print e1.Add(1, 2) -print e1.Add(1.0, 2.0) -e3 = e1.Add(e1, e2) -print e3.mPublicInt - -print e1.Add("1", "2") - -JvDetachCurrentThread() diff --git a/Examples/python/multimap/example.i b/Examples/python/multimap/example.i index 66c0f74c6..3ff5d52c0 100644 --- a/Examples/python/multimap/example.i +++ b/Examples/python/multimap/example.i @@ -39,7 +39,11 @@ extern int gcd(int x, int y); %#if PY_VERSION_HEX >= 0x03000000 { PyObject *utf8str = PyUnicode_AsUTF8String(s); - const char *cstr = PyBytes_AsString(utf8str); + const char *cstr; + if (!utf8str) { + SWIG_fail; + } + cstr = PyBytes_AsString(utf8str); $2[i] = strdup(cstr); Py_DECREF(utf8str); } @@ -72,6 +76,9 @@ extern int gcdmain(int argc, char *argv[]); SWIG_fail; } utf8str = PyUnicode_AsUTF8String($input); + if (!utf8str) { + SWIG_fail; + } PyBytes_AsStringAndSize(utf8str, &cstr, &len); $1 = strncpy((char *)malloc(len+1), cstr, (size_t)len); $2 = (int)len; @@ -105,6 +112,9 @@ extern int count(char *bytes, int len, char c); char *cstr; Py_ssize_t len; PyObject *utf8str = PyUnicode_AsUTF8String($input); + if (!utf8str) { + SWIG_fail; + } PyBytes_AsStringAndSize(utf8str, &cstr, &len); $1 = strncpy((char *)malloc(len+1), cstr, (size_t)len); $2 = (int)len; diff --git a/Examples/python/operator/example.i b/Examples/python/operator/example.i index e37e76b3e..1e4b7ce34 100644 --- a/Examples/python/operator/example.i +++ b/Examples/python/operator/example.i @@ -17,6 +17,7 @@ %include "example.h" /* An output method that turns a complex into a short string */ +%feature("python:slot", "tp_str", functype="reprfunc") Complex::__str__; // For -builtin option to use __str__ in the tp_str slot %extend Complex { char *__str__() { static char temp[512]; diff --git a/Examples/python/performance/constructor/runme.py b/Examples/python/performance/constructor/runme.py index 1771fba7b..b00cd456c 100644 --- a/Examples/python/performance/constructor/runme.py +++ b/Examples/python/performance/constructor/runme.py @@ -1,5 +1,5 @@ import sys -sys.path.append('..') +sys.path.append("..") import harness diff --git a/Examples/python/performance/func/runme.py b/Examples/python/performance/func/runme.py index 760a8ab6d..3b142791c 100644 --- a/Examples/python/performance/func/runme.py +++ b/Examples/python/performance/func/runme.py @@ -1,5 +1,5 @@ import sys -sys.path.append('..') +sys.path.append("..") import harness diff --git a/Examples/python/performance/harness.py b/Examples/python/performance/harness.py index c3d38b4fb..3468faaad 100644 --- a/Examples/python/performance/harness.py +++ b/Examples/python/performance/harness.py @@ -17,16 +17,16 @@ def run(proc): except IndexError: proc = Popen( - [sys.executable, 'runme.py', 'Simple_baseline'], stdout=PIPE) + [sys.executable, "runme.py", "Simple_baseline"], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout proc = Popen( - [sys.executable, 'runme.py', 'Simple_optimized'], stdout=PIPE) + [sys.executable, "runme.py", "Simple_optimized"], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout proc = Popen( - [sys.executable, 'runme.py', 'Simple_builtin'], stdout=PIPE) + [sys.executable, "runme.py", "Simple_builtin"], stdout=PIPE) (stdout, stderr) = proc.communicate() print stdout diff --git a/Examples/python/performance/hierarchy/runme.py b/Examples/python/performance/hierarchy/runme.py index 8255cdc86..389958284 100644 --- a/Examples/python/performance/hierarchy/runme.py +++ b/Examples/python/performance/hierarchy/runme.py @@ -1,5 +1,5 @@ import sys -sys.path.append('..') +sys.path.append("..") import harness diff --git a/Examples/python/performance/hierarchy_operator/runme.py b/Examples/python/performance/hierarchy_operator/runme.py index eabfae864..48241d48b 100644 --- a/Examples/python/performance/hierarchy_operator/runme.py +++ b/Examples/python/performance/hierarchy_operator/runme.py @@ -1,5 +1,5 @@ import sys -sys.path.append('..') +sys.path.append("..") import harness diff --git a/Examples/python/performance/operator/runme.py b/Examples/python/performance/operator/runme.py index d75ae404c..798dd8bf9 100644 --- a/Examples/python/performance/operator/runme.py +++ b/Examples/python/performance/operator/runme.py @@ -1,5 +1,5 @@ import sys -sys.path.append('..') +sys.path.append("..") import harness diff --git a/Examples/python/std_vector/example.h b/Examples/python/std_vector/example.h index 4f0dac70d..52e260d6d 100644 --- a/Examples/python/std_vector/example.h +++ b/Examples/python/std_vector/example.h @@ -17,9 +17,8 @@ std::vector<double> half(const std::vector<double>& v) { } void halve_in_place(std::vector<double>& v) { - // would you believe this is the same as the above? - std::transform(v.begin(),v.end(),v.begin(), - std::bind2nd(std::divides<double>(),2.0)); + for (std::vector<double>::iterator it = v.begin(); it != v.end(); ++it) + *it /= 2.0; } diff --git a/Examples/python/variables/runme.py b/Examples/python/variables/runme.py index 3388a0eba..4d34e92dd 100644 --- a/Examples/python/variables/runme.py +++ b/Examples/python/variables/runme.py @@ -48,18 +48,18 @@ example.print_vars() print "\nNow I'm going to try and modify some read only variables" -print " Tring to set 'path'" +print " Trying to set 'path'" try: example.cvar.path = "Whoa!" print "Hey, what's going on?!?! This shouldn't work" -except: +except Exception: print "Good." print " Trying to set 'status'" try: example.cvar.status = 0 print "Hey, what's going on?!?! This shouldn't work" -except: +except Exception: print "Good." |