<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](windows.xhtml "Python在Windows上的常見問題") | - [上一頁](library.xhtml "代碼庫和插件 FAQ") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 常見問題](index.xhtml) ? - $('.inline-search').show(0); | # [擴展/嵌入常見問題](#id3) 目錄 - [擴展/嵌入常見問題](#extending-embedding-faq) - [可以使用C語言中創建自己的函數嗎?](#can-i-create-my-own-functions-in-c) - [可以使用C++語言中創建自己的函數嗎?](#id2) - [C很難寫,有沒有其他選擇?](#writing-c-is-hard-are-there-any-alternatives) - [如何從C執行任意Python語句?](#how-can-i-execute-arbitrary-python-statements-from-c) - [如何從C中評估任意Python表達式?](#how-can-i-evaluate-an-arbitrary-python-expression-from-c) - [如何從Python對象中提取C的值?](#how-do-i-extract-c-values-from-a-python-object) - [如何使用Py\_BuildValue()創建任意長度的元組?](#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length) - [如何從C調用對象的方法?](#how-do-i-call-an-object-s-method-from-c) - [如何捕獲PyErr\_Print()(或打印到stdout / stderr的任何內容)的輸出?](#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr) - [如何從C訪問用Python編寫的模塊?](#how-do-i-access-a-module-written-in-python-from-c) - [如何從Python接口到C ++對象?](#how-do-i-interface-to-c-objects-from-python) - [我使用Setup文件添加了一個模塊,為什么make失敗了?](#i-added-a-module-using-the-setup-file-and-the-make-fails-why) - [如何調試擴展?](#how-do-i-debug-an-extension) - [我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?](#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why) - [如何區分“輸入不完整”和“輸入無效”?](#how-do-i-tell-incomplete-input-from-invalid-input) - [如何找到未定義的g++符號\_\_builtin\_new或\_\_pure\_virtual?](#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual) - [能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?](#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance) ## [可以使用C語言中創建自己的函數嗎?](#id4) 是的,您可以在C中創建包含函數、變量、異常甚至新類型的內置模塊。在文檔 [擴展和嵌入 Python 解釋器](../extending/index.xhtml#extending-index) 中有說明。 大多數中級或高級的Python書籍也涵蓋這個主題。 ## [可以使用C++語言中創建自己的函數嗎?](#id5) 是的,可以使用C ++中兼容C的功能。 在Python include文件周圍放置` extern“C”{...}` ,并在Python解釋器調用的每個函數之前放置 `extern“C”` 。 具有構造函數的全局或靜態C ++對象可能不是一個好主意。 ## [C很難寫,有沒有其他選擇?](#id6) 編寫自己的C擴展有很多選擇,具體取決于您要做的事情。 [Cython](http://cython.org) \[http://cython.org\] 及其相關的 [Pyrex](https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) \[https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/\] 是接受稍微修改過的Python形式并生成相應C代碼的編譯器。 Cython和Pyrex可以編寫擴展而無需學習Python的C API。 如果需要連接到某些當前不存在Python擴展的C或C ++庫,可以嘗試使用 [SWIG](http://www.swig.org) \[http://www.swig.org\] 等工具包裝庫的數據類型和函數。 [SIP](https://riverbankcomputing.com/software/sip/intro) \[https://riverbankcomputing.com/software/sip/intro\] , [CXX](http://cxx.sourceforge.net/) \[http://cxx.sourceforge.net/\] [Boost](http://www.boost.org/libs/python/doc/index.html) \[http://www.boost.org/libs/python/doc/index.html\] , 或 [Weave](https://github.com/scipy/weave) \[https://github.com/scipy/weave\] 也是包裝C ++庫的替代方案。 ## [如何從C執行任意Python語句?](#id7) The highest-level function to do this is [`PyRun_SimpleString()`](../c-api/veryhigh.xhtml#c.PyRun_SimpleString "PyRun_SimpleString") which takes a single string argument to be executed in the context of the module `__main__` and returns `0` for success and `-1` when an exception occurred (including [`SyntaxError`](../library/exceptions.xhtml#SyntaxError "SyntaxError")). If you want more control, use [`PyRun_String()`](../c-api/veryhigh.xhtml#c.PyRun_String "PyRun_String"); see the source for [`PyRun_SimpleString()`](../c-api/veryhigh.xhtml#c.PyRun_SimpleString "PyRun_SimpleString") in `Python/pythonrun.c`. ## [如何從C中評估任意Python表達式?](#id8) Call the function [`PyRun_String()`](../c-api/veryhigh.xhtml#c.PyRun_String "PyRun_String") from the previous question with the start symbol [`Py_eval_input`](../c-api/veryhigh.xhtml#c.Py_eval_input "Py_eval_input"); it parses an expression, evaluates it and returns its value. ## [如何從Python對象中提取C的值?](#id9) That depends on the object's type. If it's a tuple, [`PyTuple_Size()`](../c-api/tuple.xhtml#c.PyTuple_Size "PyTuple_Size")returns its length and [`PyTuple_GetItem()`](../c-api/tuple.xhtml#c.PyTuple_GetItem "PyTuple_GetItem") returns the item at a specified index. Lists have similar functions, `PyListSize()` and [`PyList_GetItem()`](../c-api/list.xhtml#c.PyList_GetItem "PyList_GetItem"). For bytes, [`PyBytes_Size()`](../c-api/bytes.xhtml#c.PyBytes_Size "PyBytes_Size") returns its length and [`PyBytes_AsStringAndSize()`](../c-api/bytes.xhtml#c.PyBytes_AsStringAndSize "PyBytes_AsStringAndSize") provides a pointer to its value and its length. Note that Python bytes objects may contain null bytes so C's `strlen()` should not be used. 要測試對象的類型,首先要確保它不是 *NULL* ,然后使用 [`PyBytes_Check()`](../c-api/bytes.xhtml#c.PyBytes_Check "PyBytes_Check") , [`PyTuple_Check()`](../c-api/tuple.xhtml#c.PyTuple_Check "PyTuple_Check") , [`PyList_Check()`](../c-api/list.xhtml#c.PyList_Check "PyList_Check") 等 There is also a high-level API to Python objects which is provided by the so-called 'abstract' interface -- read `Include/abstract.h` for further details. It allows interfacing with any kind of Python sequence using calls like [`PySequence_Length()`](../c-api/sequence.xhtml#c.PySequence_Length "PySequence_Length"), [`PySequence_GetItem()`](../c-api/sequence.xhtml#c.PySequence_GetItem "PySequence_GetItem"), etc. as well as many other useful protocols such as numbers ([`PyNumber_Index()`](../c-api/number.xhtml#c.PyNumber_Index "PyNumber_Index") et al.) and mappings in the PyMapping APIs. ## [如何使用Py\_BuildValue()創建任意長度的元組?](#id10) 不可以。應該使用 [`PyTuple_Pack()`](../c-api/tuple.xhtml#c.PyTuple_Pack "PyTuple_Pack") 。 ## [如何從C調用對象的方法?](#id11) The [`PyObject_CallMethod()`](../c-api/object.xhtml#c.PyObject_CallMethod "PyObject_CallMethod") function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to call, a format string like that used with [`Py_BuildValue()`](../c-api/arg.xhtml#c.Py_BuildValue "Py_BuildValue"), and the argument values: ``` PyObject * PyObject_CallMethod(PyObject *object, const char *method_name, const char *arg_format, ...); ``` This works for any object that has methods -- whether built-in or user-defined. You are responsible for eventually [`Py_DECREF()`](../c-api/refcounting.xhtml#c.Py_DECREF "Py_DECREF")'ing the return value. To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the file object pointer is "f"): ``` res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0); if (res == NULL) { ... an exception occurred ... } else { Py_DECREF(res); } ``` Note that since [`PyObject_CallObject()`](../c-api/object.xhtml#c.PyObject_CallObject "PyObject_CallObject") *always* wants a tuple for the argument list, to call a function without arguments, pass "()" for the format, and to call a function with one argument, surround the argument in parentheses, e.g. "(i)". ## [如何捕獲PyErr\_Print()(或打印到stdout / stderr的任何內容)的輸出?](#id12) In Python code, define an object that supports the `write()` method. Assign this object to [`sys.stdout`](../library/sys.xhtml#sys.stdout "sys.stdout") and [`sys.stderr`](../library/sys.xhtml#sys.stderr "sys.stderr"). Call print\_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your `write()` method sends it. The easiest way to do this is to use the [`io.StringIO`](../library/io.xhtml#io.StringIO "io.StringIO") class: ``` >>> import io, sys >>> sys.stdout = io.StringIO() >>> print('foo') >>> print('hello world!') >>> sys.stderr.write(sys.stdout.getvalue()) foo hello world! ``` A custom object to do the same would look like this: ``` >>> import io, sys >>> class StdoutCatcher(io.TextIOBase): ... def __init__(self): ... self.data = [] ... def write(self, stuff): ... self.data.append(stuff) ... >>> import sys >>> sys.stdout = StdoutCatcher() >>> print('foo') >>> print('hello world!') >>> sys.stderr.write(''.join(sys.stdout.data)) foo hello world! ``` ## [如何從C訪問用Python編寫的模塊?](#id13) You can get a pointer to the module object as follows: ``` module = PyImport_ImportModule("<modulename>"); ``` If the module hasn't been imported yet (i.e. it is not yet present in [`sys.modules`](../library/sys.xhtml#sys.modules "sys.modules")), this initializes the module; otherwise it simply returns the value of `sys.modules["<modulename>"]`. Note that it doesn't enter the module into any namespace -- it only ensures it has been initialized and is stored in [`sys.modules`](../library/sys.xhtml#sys.modules "sys.modules"). You can then access the module's attributes (i.e. any name defined in the module) as follows: ``` attr = PyObject_GetAttrString(module, "<attrname>"); ``` Calling [`PyObject_SetAttrString()`](../c-api/object.xhtml#c.PyObject_SetAttrString "PyObject_SetAttrString") to assign to variables in the module also works. ## [如何從Python接口到C ++對象?](#id14) Depending on your requirements, there are many approaches. To do this manually, begin by reading [the "Extending and Embedding" document](../extending/index.xhtml#extending-index). Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects. 有關C ++庫,請參閱 [C很難寫,有沒有其他選擇?](#c-wrapper-software) ## [我使用Setup文件添加了一個模塊,為什么make失敗了?](#id15) 安裝程序必須以換行符結束,如果沒有換行符,則構建過程將失敗。 (修復這個需要一些丑陋的shell腳本編程,而且這個bug很小,看起來不值得花這么大力氣。) ## [如何調試擴展?](#id16) 將GDB與動態加載的擴展名一起使用時,在加載擴展名之前,不能在擴展名中設置斷點。 在您的 `.gdbinit` 文件中(或交互式)添加命令: ``` br _PyImport_LoadDynamicModule ``` 然后運行GDB: ``` $ gdb /local/bin/python gdb) run myscript.py gdb) continue # repeat until your extension is loaded gdb) finish # so that your extension is loaded gdb) br myfunction.c:50 gdb) continue ``` ## [我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?](#id17) 大多數打包的Python版本不包含 `/usr/lib/python2.x/config/` 目錄,該目錄中包含編譯Python擴展所需的各種文件。 對于Red Hat,安裝python-devel RPM以獲取必要的文件。 對于Debian,運行 `apt-get install python-dev` 。 ## [如何區分“輸入不完整”和“輸入無效”?](#id18) 有時,希望模仿Python交互式解釋器的行為,在輸入不完整時(例如,您鍵入了“if”語句的開頭,或者沒有關閉括號或三個字符串引號),給出一個延續提示,但當輸入無效時,立即給出一條語法錯誤消息。 在Python中,您可以使用 [`codeop`](../library/codeop.xhtml#module-codeop "codeop: Compile (possibly incomplete) Python code.") 模塊,該模塊非常接近解析器的行為。例如,IDLE就使用了這個。 在C中執行此操作的最簡單方法是調用 [`PyRun_InteractiveLoop()`](../c-api/veryhigh.xhtml#c.PyRun_InteractiveLoop "PyRun_InteractiveLoop") (可能在單獨的線程中)并讓Python解釋器為您處理輸入。您還可以設置 [`PyOS_ReadlineFunctionPointer()`](../c-api/veryhigh.xhtml#c.PyOS_ReadlineFunctionPointer "PyOS_ReadlineFunctionPointer") 指向您的自定義輸入函數。有關更多提示,請參閱 `Modules/readline.c` 和 `Parser/myreadline.c` 。 但是,有時必須在與其他應用程序相同的線程中運行嵌入式Python解釋器,并且不能允許 [`PyRun_InteractiveLoop()`](../c-api/veryhigh.xhtml#c.PyRun_InteractiveLoop "PyRun_InteractiveLoop") 在等待用戶輸入時停止。那么另一個解決方案是調用 `PyParser_ParseString()` 并測試 `e.error` 等于 `E_EOF` ,如果等于,就意味著輸入不完整。這是一個示例代碼片段,未經測試,靈感來自Alex Farber的代碼: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> #include <node.h> #include <errcode.h> #include <grammar.h> #include <parsetok.h> #include <compile.h> int testcomplete(char *code) /* code should end in \n */ /* return -1 for error, 0 for incomplete, 1 for complete */ { node *n; perrdetail e; n = PyParser_ParseString(code, &_PyParser_Grammar, Py_file_input, &e); if (n == NULL) { if (e.error == E_EOF) return 0; return -1; } PyNode_Free(n); return 1; } ``` 另一個解決方案是嘗試使用 [`Py_CompileString()`](../c-api/veryhigh.xhtml#c.Py_CompileString "Py_CompileString") 編譯接收到的字符串。如果編譯時沒有出現錯誤,請嘗試通過調用 [`PyEval_EvalCode()`](../c-api/veryhigh.xhtml#c.PyEval_EvalCode "PyEval_EvalCode") 來執行返回的代碼對象。否則,請將輸入保存到以后。如果編譯失敗,找出是錯誤還是只需要更多的輸入-從異常元組中提取消息字符串,并將其與字符串 “分析時意外的EOF” 進行比較。下面是使用GNUreadline庫的完整示例(您可能希望在調用readline()時忽略 **SIGINT** ): ``` #include <stdio.h> #include <readline.h> #define PY_SSIZE_T_CLEAN #include <Python.h> #include <object.h> #include <compile.h> #include <eval.h> int main (int argc, char* argv[]) { int i, j, done = 0; /* lengths of line, code */ char ps1[] = ">>> "; char ps2[] = "... "; char *prompt = ps1; char *msg, *line, *code = NULL; PyObject *src, *glb, *loc; PyObject *exc, *val, *trb, *obj, *dum; Py_Initialize (); loc = PyDict_New (); glb = PyDict_New (); PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ()); while (!done) { line = readline (prompt); if (NULL == line) /* Ctrl-D pressed */ { done = 1; } else { i = strlen (line); if (i > 0) add_history (line); /* save non-empty lines */ if (NULL == code) /* nothing in code yet */ j = 0; else j = strlen (code); code = realloc (code, i + j + 2); if (NULL == code) /* out of memory */ exit (1); if (0 == j) /* code was empty, so */ code[0] = '\0'; /* keep strncat happy */ strncat (code, line, i); /* append line to code */ code[i + j] = '\n'; /* append '\n' to code */ code[i + j + 1] = '\0'; src = Py_CompileString (code, "<stdin>", Py_single_input); if (NULL != src) /* compiled just fine - */ { if (ps1 == prompt || /* ">>> " or */ '\n' == code[i + j - 1]) /* "... " and double '\n' */ { /* so execute it */ dum = PyEval_EvalCode (src, glb, loc); Py_XDECREF (dum); Py_XDECREF (src); free (code); code = NULL; if (PyErr_Occurred ()) PyErr_Print (); prompt = ps1; } } /* syntax error or E_EOF? */ else if (PyErr_ExceptionMatches (PyExc_SyntaxError)) { PyErr_Fetch (&exc, &val, &trb); /* clears exception! */ if (PyArg_ParseTuple (val, "sO", &msg, &obj) && !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */ { Py_XDECREF (exc); Py_XDECREF (val); Py_XDECREF (trb); prompt = ps2; } else /* some other syntax error */ { PyErr_Restore (exc, val, trb); PyErr_Print (); free (code); code = NULL; prompt = ps1; } } else /* some non-syntax error */ { PyErr_Print (); free (code); code = NULL; prompt = ps1; } free (line); } } Py_XDECREF(glb); Py_XDECREF(loc); Py_Finalize(); exit(0); } ``` ## [如何找到未定義的g++符號\_\_builtin\_new或\_\_pure\_virtual?](#id19) 要動態加載g ++擴展模塊,必須重新編譯Python,要使用g ++重新鏈接(在Python Modules Makefile中更改LINKCC),及鏈接擴展模塊(例如: `g++ -shared -o mymodule.so mymodule.o` )。 ## [能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?](#id20) 是的,您可以繼承內置類,例如 [`int`](../library/functions.xhtml#int "int") , [`list`](../library/stdtypes.xhtml#list "list") , [`dict`](../library/stdtypes.xhtml#dict "dict") 等。 Boost Python庫(BPL,http://www.boost.org/libs/python/doc/index.html)提供了一種從C ++執行此操作的方法(即,您可以使用BPL繼承自C ++編寫的擴展類 )。 ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](windows.xhtml "Python在Windows上的常見問題") | - [上一頁](library.xhtml "代碼庫和插件 FAQ") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 常見問題](index.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看