Process输入流输出流及对C++、Python的测试

本文介绍了一个C++程序与Java及Python程序之间的交互测试案例。详细解释了如何避免因输入输出流处理不当导致的阻塞问题,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


对C++部分的测试来自文章:
http://fair-jm.iteye.com/blog/1442267

C++代码

    #include<iostream>  
    #include<string>  
    using namespace std;  
      
    void main(){  
        cout<<"hello world"<<endl;  
        string i;  
        cin>>i;  
        cout<<i;  
    }  








以上是试验目标的C++程序
以下是试验用的java程序:
Java代码

 
  import java.io.*;  
      
    public class TestDemo  
    {    
        Process pc;  
        Runtime rt;  
        public TestDemo() throws Exception{  
          rt=Runtime.getRuntime();  
          String [] ss={"E:\\work\\Demo\\src\\Test.exe"};  
          pc=rt.exec(ss);  
          //readIt(); 注意这样也会产生堵塞  
          writeIt();  
           
      
        }  
      
        public static void main(String args[]) throws Exception{  
            new TestDemo();  
        }  
      
            public void writeIt(){  
              OutputStream fos=pc.getOutputStream();  
              PrintStream ps=new PrintStream(fos);  
              ps.print("another\n");  
              ps.flush(); //不加这个 后面的read就读不下去了  
              readIt();  
          }  
      
            public void readIt(){  
             InputStream ios=pc.getInputStream();  
             BufferedReader br=new BufferedReader(new InputStreamReader(ios));  
             String s;  
             try{  
             while((s=br.readLine())!=null){  
             System.out.println(s);  
              }  
             br.close();  
             ios.close();  
             }catch(Exception e){  
                 e.printStackTrace();  
             }  
            }  
         
    }  





以上的做法 如果ReadIt()先写 则又会产生堵塞 所以最好用线程解决之。
堵塞的产生:你先读取输入流(相当于被调用程序的输出流getInputStream)的话 如果遇到输入的地方(cin)则输入流堵塞,
等待输入(如果不用线程的话就一直堵在那,根本无法通过输出流(相当于被调用程序的输入流)无法输入信息到进程里面去)。
如果你先用输出流输入到被调用程序里面去,但遗忘了用flush(),则数据根本就无法传输。


以下是线程的解决方法:
Java代码


package aa;  
import java.io.*;  
 
public class TestDemo  
{    
    Process pc;  
    Runtime rt;  
    public TestDemo() throws Exception{  
      rt=Runtime.getRuntime();  
      String [] ss={"E:\\work\\Demo\\src\\Test.exe"};  
      pc=rt.exec(ss);   
      new Thread(new Input()).start();  
      Thread.sleep(500);  
      new Thread(new Output()).start();  
 
 
      
 
    }  
 
    public static void main(String args[]) throws Exception{  
        new TestDemo();  
    }  
 
    class Output implements Runnable  
    {  
        public void run(){  
          OutputStream fos=pc.getOutputStream();  
          PrintStream ps=new PrintStream(fos);  
          ps.print("another\n");  
          System.out.println("已经输出");  
          ps.flush();  
      }  
    }  
 
    class Input implements Runnable  
    {  
      
        public void run(){  
         InputStream ios=pc.getInputStream();  
 BufferedReader brd=new BufferedReader(new InputStreamReader(ios));  
         String s;  
         try{  
         while((s=brd.readLine())!=null){  
         System.out.println(s);  
          }  
         }catch(Exception e){  
         }  
          pc.destroy();  
        }  
    }  
}  






以下是对python的测试:java代码:
    public static void main(String args[]) {
        rt = Runtime.getRuntime();
        String ss = "python C:\\Users\\ciabok\\Desktop\\test.py";
        try {
            pc = rt.exec(ss);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // readIt(); 注意这样也会产生堵塞
        writeIt();
    }




python代码:
# -*- coding=utf-8  -*-

if __name__=='__main__':
    print 'test'
    a=raw_input()
    print  a





经过测试,如果写成    a=input() 会无法读取,
原因不明,暂时没找到相关资料。



### 在 VSCode 中通过 C++ 调用 Python 代码的方法 要在 Visual Studio Code (VSCode) 中实现 C++ 对 Python 的调用,可以利用 `Py_Initialize` 和 `Py_Finalize` 函数来初始化和结束 Python 解释器[^1]。以下是具体方法: #### 方法一:嵌入式方式调用 Python 可以通过 Python/C API 来直接在 C++ 程序中运行 Python 代码。这需要链接 Python 库并编写相应的接口。 ```cpp #include <Python.h> #include <iostream> int main() { Py_Initialize(); // 初始化 Python 解释器 PyObject* pModule = nullptr; const char* moduleName = "example"; // 替换为实际的模块名 // 加载 Python 模块 pModule = PyImport_ImportModule(moduleName); if (!pModule) { PyErr_Print(); std::cerr << "Failed to load module." << std::endl; return -1; } // 获取函数对象 PyObject* pFunc = PyObject_GetAttrString(pModule, "my_function"); // 替换为实际的函数名 if (!pFunc || !PyCallable_Check(pFunc)) { PyErr_Print(); std::cerr << "Cannot find function 'my_function'." << std::endl; return -1; } // 调用函数 PyObject* pArgs = PyTuple_Pack(1, PyUnicode_FromString("Hello from C++")); // 参数列表 PyObject* pResult = PyObject_CallObject(pFunc, pArgs); if (pResult != nullptr) { std::cout << "Function returned: " << PyUnicode_AsUTF8(pResult) << std::endl; // 输出返回值 Py_DECREF(pResult); // 清理资源 } else { PyErr_Print(); } // 清理内存 Py_XDECREF(pArgs); Py_XDECREF(pFunc); Py_XDECREF(pModule); Py_Finalize(); // 结束解释器 return 0; } ``` 此代码片段展示了如何加载一个名为 `example.py` 的模块,并调用其中定义的一个函数 `my_function`[^2]。 #### 配置环境 为了使上述程序正常工作,在 VSCode 中需完成以下配置: 1. 安装 Python 开发库(通常位于操作系统包管理器或 Python 官方安装文件中)。 2. 设置编译选项以包含 Python 头文件路径以及链接动态库。例如,对于 Linux 用户可能需要设置 `-I/usr/include/python3.x` 并链接 `-lpython3.x`;Windows 则应指定对应的 `.lib` 文件位置[^3]。 #### 方法二:子进程执行 Python 脚本 另一种更简单的方式是通过标准输入/输出流与独立运行的 Python 进程通信。这种方法无需处理复杂的跨语言交互细节。 ```cpp #include <iostream> #include <cstdlib> int main(){ FILE *pipe = popen("python3 script.py", "r"); if(!pipe){ perror("Error opening pipe."); exit(EXIT_FAILURE); } char buffer[128]; while(fgets(buffer, sizeof(buffer), pipe)!=NULL){ printf("%s",buffer); } int ret=pclose(pipe); if(ret==EXIT_SUCCESS){ puts("Script executed successfully!"); }else{ fprintf(stderr,"Child process exited with error code %d.\n",ret); } return EXIT_SUCCESS; } ``` 这里演示了启动外部脚本并通过管道读取其输出的过程[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值