Python调用C++_subprocess

C++文件

编译的动态库,头文件和库文件
    头文件,也就是 .h   后缀的文件 
 静态库文件,也就是 .lib 文件   库文件通常以.a结尾
 动态库文件,也就是 .dll 文件   库文件通常以.so结尾
 可执行文件:.exe 文件   .out文件  

 python 调用 C++ 可执行程序 exe  .out文件   并传递参数
 python 调用 C++ 动态库文件(后缀名为 .so) dll

Python 调用C++ 可执行程序 exe 并传递参数

// 说明  cpptest.cpp
// 编译命令  //g++ -o cpptest  cpptest.cpp
 #include<iostream>
 #include<string.h>
 using namespace std;
 int main(int argc,char* argv[])
 {
     for(int x = 0;x< argc;x++)
     {
         cout<<x<<" : "<<argv[x]<<endl;
     }
     return 0;
 }
##python 文件	 
 import os
 import subprocess
 string_para = "sssss"
 int_para = 10
 os.system(r'./cpptest "abcd" '+ string_para+r' '+str(int_para))##注意每个参数之间必须用空格隔开
 subprocess.run([hdfs_mkdir], shell=True, encoding="utf-8")
 subprocess.check_output(['ls', '-alh'], shell = False)
 subprocess.check_output(static_file, shell = True).decode(encoding="utf-8").strip("\r\n")
 
  说明:
     os模块中提供了两种调用 cmd 的方法,os.popen() 和 os.system()	

代码示例

class Solution {
public:
int lengthOfLastWord(string s) {
    int ans=0;
    int i=s.length();
    int flag=0;
    while(i--){
         if(s[i]!=' '){
              ans++;
              flag=1;
            }
         if(s[i]==' '&&flag==1){
                break;
           }
    }
    return ans;
    }
};

subprocess

subprocess.run([unzip_cmd], shell=True, encoding="utf-8")
     shell 如果该参数为True,将通过操作系统的shell执行指定的命令

subprocess.call()
      父进程等待子进程完成,并且返回子进程执行的结果 0/1 其实现方式
subprocess.check_call()

subprocess.check_output
     return the data as encoded bytes
     其返回的结果是执行命令的输出,而非返回0/1 
	 output = subprocess.check_output(static_file, shell = True).decode(encoding="utf-8")
     output = subprocess.check_output(["python3", "xx.py"], shell = False)
	 
	 info= output.split("\n")
	 for data in info:
	     print(data.strip("\r\n"))
    说明
    #通过 decode() 方法将 bytes 转换成字符串
       str1 = b5.decode('UTF-8')
    
    #通过 encode() 方法将字符串转换成 bytes
        b5 = "C了".encode('UTF-8')
		
Popen基本格式:subprocess.Popen(‘命令’, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)	
    shell=True 表示要在终端中运行的命令
    stdout=sbuprocess.PIPE 表示当命令存在的时候,把结果写入到stdout管道	

参考

  python调用C++ 程序 https://blog.csdn.net/shanglianlm/article/details/88691044
posted @ 2022-05-12 22:19  辰令  阅读(459)  评论(0编辑  收藏  举报