加入收藏 | 设为首页 | 会员中心 | 我要投稿 应用网_丽江站长网 (http://www.0888zz.com/)- 科技、建站、数据工具、云上网络、机器学习!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Python容易技巧和常用参考

发布时间:2022-07-24 00:06:02 所属栏目:PHP教程 来源:互联网
导读:python文件支持中文 # -*- coding: UTF-8 -*- 执行shell命令 from subprocess import Popen, PIPE def run_cmd(cmd): #Popen call wrapper.return (code, stdout, stderr) child = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = True)
  python文件支持中文
 
  # -*- coding: UTF-8 -*-
 
  执行shell命令
 
  from subprocess import Popen, PIPE
 
  def run_cmd(cmd):
 
      #Popen call wrapper.return (code, stdout, stderr)
 
      child = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = True)
 
      out, err = child.communicate()
 
      ret = child.wait()
 
      return (ret, out, err)
 
  获取当前python脚本文件所在路径
 
  import os
 
  os.path.split(os.path.realpath(__file__))[0]
 
  一般调用步骤
 
  Py_Initialize(); //初始化Python环境
 
  PyImport_ImportModule("test"); // 载入python模块
 
  PyObject_GetAttrString(g_pModule,"test1"); //获得相应Python函数的PyObject
 
  PyObject_CallFunction(test1,"i,s",2,e); //调用Python相应的函数
 
  Py_Finalize(); //结束
 
  C语言的示例代码
 Python容易技巧和常用参考
  #include <python2.7/Python.h>
 
  int main(){
 
          PyObject * test1 = PyObject_GetAttrString(g_pModule,"test1");//这里是要调用的函数名
 
          PyObject *objResult =  PyObject_CallFunction(test1,"i,s",2,e);//调用函数
 
          if (!objResult){
 
              printf("invoke function fail\n");
 
          }
 
          PyObject * test2= PyObject_GetAttrString(g_pModule,"test2");//这里是要调用的函数名
 
          objResult =  PyObject_CallFunction(test2,"i",2);//调用函数
 
          char * x = PyString_AsString(objResult);
 
          printf("%s\n",x);
 
         Py_Finalize();//调用Py_Finalize,这个跟Py_Initialize相对应的。
  }
 
  Python程序mytest.py
 
  def test1(s,str):
 
      print s+str
 
      return 0
 
  def test2(s):
 
      return s
 
  C程序的编译方法
 
  #假设我们的python编译的时候安装在/opt/python里,那么我们可以用这样的命令来编译程序
 
  $gcc -I/opt/python/include -L/opt/python/lib/ -lpython2.7 test.c
 
  注意: 这里要求python编译的时候,需要有动态链接库即加上--enable-shared
 
  ./configure --prefix=/opt/python  --enable-shared。
 

(编辑:应用网_丽江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读