Tips for Python beginners to use the Scikit-image example for themselves 9 Use from C

Throughout the series so far, the example (Note 2) in scikit-image Move as it is, Change input file, Handle multiple input files Write the result to a file Use GUI Link with network Improve code and Reuse as module Measuring and profiling processing time was shown.

Once you've mastered it that far, you'll probably want to use it from the C / C ++ language next time.

So this time, I will introduce how to use Python from C / C ++ language.

Use Python from C / C ++ language

** 1. Use of system function and popen function **

python script with system () function system("python myscript.py"); By doing so, Python can be used from C language. fp=popen("python myscript.py","r"); As a result, you can receive the result as well as execute it.

For the time being, this method can be performed without difficulty as long as you can use C language.

Challenges for this method: Every time the process is executed, the python interpreter is started by system or popen, which causes the overhead. And if the Python script you run needs to read a learned file in preparation for processing, the overhead can be very high.

** 2. Embedding Python in other applications **

Python standard documentation [Embedding Python into other applications] (http://docs.python.jp/2/extending/embedding.html)

Python standard documentation 5.3. Pure embedding

The program is for executing functions in Python scripts.

This approach does not spawn extra processes. You can pass arguments to the embedded Python part and receive the result.

PyImport_Import(pName) The name of the module read in In this example, we give the name of the python module here and execute the functions contained in that module. (To be precise, it seems that Python specifies the module name to be imported and calls the module (.py, .pyc, .pyd, etc.) in the current directory according to the setting of its PYTHONPATH. If you include a directory structure such as "$ call ../multiply multiply 3 2" in the argument of this example, PyImport_Import () fails. )

Increase the number of functions included in the module You can do the following:

.py:intmath.py


def multiply(a,b):
    print "Will compute", a, "times", b
    c = 0
    for i in range(0, a):
        c = c + b
    return c

def add(a,b):
    print "Will compute", a, " plus ", b
    return a+b

def div(a,b):
    print "Will compute", a, " div ", b
    return a/b

Execution result

.txt:Execution result.txt


>call.exe intmath div 5 2
Will compute 5  div  2
Result of call: 2
2

>call.exe intmath multiply 6 3

Will compute 6 times 3
Result of call: 18
18

>call.exe intmath add 6 3
Will compute 6  plus  3
Result of call: 9
9

>

It can also be done like this.

This example is very dangerous because it doesn't check the values entered from the command line.

You can convert Python objects to C data structures as follows: long PyInt_AsLong(PyObject *io) http://docs.python.jp/2/c-api/int.html

double PyFloat_AsDouble(PyObject *pyfloat) http://docs.python.jp/2/c-api/float.html

By embedding it in this way and using it from C language, it is possible to eliminate the overhead of starting the python interpreter and repeating the termination with the system () function and popen () function. In addition, it should be noted Py_Initialize(); pModule = PyImport_Import(pName); Py_Finalize(); It's also important to ensure that you only run when you really need it.

effect: The C / C ++ language side has the advantage that no matter how the implementation of the Python module changes, there is no need to rebuild it, as long as the interface of the calling module, function, argument, and return value does not change.

I'm still studying [Note 1].

In the example program of 5.3. Pure embedding Since the function arguments and return values are integer types, let's create a program that just replaces them with floating point numbers.

Writing an embedded program requires a good understanding of both Python and C, and may require an obsession with getting it working. It's quite unusual for a Python programmer to be familiar with Python embedding just because you have a Python user around you. So, let's write a program that has been slightly rewritten and try to imitate it.

** Addition: When you cannot build in Debug mode **

LINK : fatal error LNK1104: cannot open file 'python27_d.lib' Is displayed in Visual Studio. How to use python27.lib in both Release mode and Debug mode as follows stackoverflow It was written in.

#ifdef _DEBUG
  #undef _DEBUG
  #include <Python.h>
  #define _DEBUG
#else
  #include <Python.h>
#endif

Note: I tried to display the process in the task manager while embedding and using Python. Even when I executed the Python module part, I was able to confirm that the python.exe process was not created. If you are using the system command or popen, please try embedding because you will not have to repeat starting Python and initial settings in the script many times.


Things to write, etc. Boost.Python C ++ embedded in Python with Scipy.Weave Cython Numpy C-API Scipy Python Types and C-Structures

Note 1: When increasing the number of libraries linked with C / C ++, "This library needs that library, that library needs somehow more library, and if you do not link it, the part that was up to now will be built. I can't even do it. " It tends to be a sad situation. In the case of embedding Python in the C / C ++ language, the link is written here #include <Python.h> A module that contains a line for. This part is the bridge between the C / C ++ language and the Python language. The rest of the Python language is not linked. That's why you can give the module name to import in the example C program as a command line argument. It suffices to have a Python interpreter and a range of python libraries installed. "This module, that module, and which module" It's also nice to be able to prevent an endless increase in the number of objects to be linked.

Note: In the case of Visual Studio on Windows, it is specified that it cannot be linked if the compiler version changes. This can be tricky when building huge libraries like OpenCV. When generating a library for Python from the C / C ++ extension, Cython language, the version of Visual Studio must be the same.

Note 2: The reason I chose the example in Scikit-image is that when I run the example, I don't have the problem of "where should I get the necessary data?".

Recommended Posts

Tips for Python beginners to use the Scikit-image example for themselves 9 Use from C
Tips for Python beginners to use the Scikit-image example for themselves
Tips for Python beginners to use the Scikit-image example for themselves 6 Improve Python code
Tips for Python beginners to use the Scikit-image example for themselves 2 Handle multiple files
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
Tips for Python beginners to use the Scikit-image example for themselves 8 Processing time measurement and profiler
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
Tips for Python beginners to use Scikit-image examples for themselves 3 Write to a file
Tips for Python beginners to use Scikit-image examples for themselves 5 Incorporate into network apps
~ Tips for beginners to Python ③ ~
Tips for calling Python from C
How to use the C library in Python
The fastest way for beginners to master Python
Tips for manipulating numpy.ndarray from c ++ -I want to use an iterator-
Wrap C with Cython for use from Python
~ Tips for Python beginners from Pythonista with love ① ~
Wrap C ++ with Cython for use from Python
~ Tips for Python beginners from Pythonista with love ② ~
[For beginners] How to use say command in python!
I wanted to use the Python library from MATLAB
[python] How to use the library Matplotlib for drawing graphs
[For beginners] Script within 10 lines (4. Connection from python to sqlite3)
I didn't know how to use the [python] for statement
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
Pass OpenCV data from the original C ++ library to Python
Use the Flickr API from Python
Beginners use Python for web scraping (1)
Beginners use Python for web scraping (4) ―― 1
[Introduction to Python] How to use the in operator in a for statement?
[Python] Explains how to use the format function with an example
I want to use jar from python
[Python] Organizing how to use for statements
Python> Output numbers from 1 to 100, 501 to 600> For csv
How to use "deque" for Python data
Use C ++ functions from python with pybind11
An introduction to Python for C programmers
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
[Python] Explains how to use the range function with a concrete example
[Example of Python improvement] What is the recommended learning site for Python beginners?
Procedure from AWS CDK (Python) development to AWS resource construction * For beginners of development
How to use MkDocs for the first time
Python for super beginners Python for super beginners # Easy to get angry
Study from Python Hour7: How to use classes
Tips for those who are wondering how to use is and == in Python
Specify the Python executable to use with virtualenv
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Use logger with Python for the time being
[Bash] Use here-documents to get python power from bash
Memo # 1 for Python beginners to read "Detailed Python Grammar"
How to use data analysis tools for beginners
Tips for hitting the ATND API in Python
Use PIL in Python to extract only the data you want from Exif
The easiest way to use OpenCV with python
Try to calculate RPN in Python (for beginners)
[Algorithm x Python] How to use the list
Use the Python framework "cocotb" to test Verilog.
Memo # 2 for Python beginners to read "Detailed Python Grammar"
I want to use ceres solver from python
Memo # 7 for Python beginners to read "Detailed Python Grammar"
[Python Tips] How to retrieve multiple keys with the maximum value from the dictionary
I want to make C ++ code from Python code!