C++和java调用Python(Python2.7)

1、java调用Python(无参数)

#coding:utf-8
def sum():
    print "hello world"
if __name__ == '__main__':
    sum()
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test7 {
	public static void main(String[] args) throws Exception {
        System.out.println("start");
        String[] path = new String[] { "python", "C:\\Users\\HQH\\Desktop\\demo.py"}; 
        Process pr=Runtime.getRuntime().exec(path);
        BufferedReader in = new BufferedReader(new InputStreamReader(
          pr.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
        	System.out.println(line);
        }
        in.close();
        pr.waitFor();
        System.out.println("end");
	}
}
2、java调用Python(有参数)

#coding:utf-8
import sys
def sum(a,b):
    print a+'+'+b+'='+str(int(a)+int(b))
if __name__ == '__main__':
    a=[]
    #遍历传参从1开始
    for i in range(1, len(sys.argv)):
        num = sys.argv[i]
        a.append(num)
    #存储参数从0开始,数据类型为Str
    sum(a[0],a[1])
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class test8 {
	public static void main(String[] args) throws Exception {
		System.out.println("请输入两个整数:");
		Scanner cin=new Scanner(System.in);
		String num1=cin.next();
		String num2=cin.next();
		
        System.out.println("start");
        String[] path = new String[] { "python", "C:\\Users\\HQH\\Desktop\\demo1.py", num1,num2}; 
        Process pr=Runtime.getRuntime().exec(path);
        BufferedReader in = new BufferedReader(new InputStreamReader(
          pr.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
        	System.out.println(line);
        }
        in.close();
        pr.waitFor();
        System.out.println("end");
	}
}
3、C++调用Python

配置VS环境:

①添加include下文件
如:D:\Python27\include
项目>属性>C/C++>常规>附加包含目录下
②添加libs下文件
如:D:\Python27\libs
1)项目>属性>配置属性>VC++目录>库目录

2)项目>属性>配置属性>链接器>常规>附加库目录

测试代码:

#include "Python.h"
#include<iostream>
using namespace std;
int main()
{
	Py_Initialize();    //初始化
		PyRun_SimpleString("print 'hello'");
	Py_Finalize();      // 释放资源
	system("pause");
}
出错调试:

python27_d.lib找不到,打开源码,删除即可(pyconfig.h)

注意加载路径,模块名,函数名,传参与否

def test_add(a, b):
    print 'add ', a, ' and ', b
    return a+b
#include "Python.h"
#include <iostream>
using namespace std;
int main()
{
	Py_Initialize();    // 初始化
	// 模块所在路径
	string chdir_cmd = string("sys.path.append('C:/Users/HQH/Desktop')");
	const char* cstr_cmd = chdir_cmd.c_str();
	//导入sys,添加模块路径
	PyRun_SimpleString("import sys");
	PyRun_SimpleString(cstr_cmd);
	// 加载模块
	PyObject* moduleName = PyString_FromString("demo2"); //模块名,demo2.py
	PyObject* pModule = PyImport_Import(moduleName);
	if (!pModule) // 加载模块失败
	{
		cout << "[ERROR] Python get module failed." << endl;
		return 0;
	}
	cout << "[INFO] Python get module succeed." << endl;
	// 加载函数
	PyObject* pv = PyObject_GetAttrString(pModule, "test_add");
	if (!pv || !PyCallable_Check(pv))  // 验证是否加载成功
	{
		cout << "[ERROR] Can't find funftion (test_add)" << endl;
		return 0;
	}
	cout << "[INFO] Get function (test_add) succeed." << endl;
	// 设置参数
	PyObject* args = PyTuple_New(2);       // 2个参数
	PyObject* arg1 = PyInt_FromLong(4);    // 参数一设为4
	PyObject* arg2 = PyInt_FromLong(3);    // 参数二设为3
	PyTuple_SetItem(args, 0, arg1);
	PyTuple_SetItem(args, 1, arg2);
	// 调用函数
	PyObject* pRet = PyObject_CallObject(pv, args);
	// 获取参数
	if (pRet)  // 验证是否调用成功
	{
		long result = PyInt_AsLong(pRet);
		cout << "result:" << result<<endl;
	}
	Py_Finalize();      // 释放资源
	system("pause");
	return 0;
}
总结:

①Java调用Python,是调用全部,也就是运行这个模块
②C++调用Python,只是调用一个函数。

猜你喜欢

转载自blog.csdn.net/hqh131360239/article/details/79492254
今日推荐