📜  用于执行用不同语言编写的程序的Python子进程模块

📅  最后修改于: 2022-05-13 01:54:56.125000             🧑  作者: Mango

用于执行用不同语言编写的程序的Python子进程模块

Python(2.x 和 3.x)中存在的 subprocess 模块用于通过创建新进程来通过Python代码运行新的应用程序或程序。它还有助于获取输入/输出/错误管道以及各种命令的退出代码。

为了使用Python执行不同的程序,使用了 subprocess 模块的两个函数:

让我们考虑以下示例:

C程序:

#include
int main()
{
    printf("Hello World from C");
  
    // returning with any other non zero value
    // would result in an exception
    // when called from python
    return 0;
}

C++程序:

#include 
using namespace std;
int main()
{
    int a, b;
    cin >> a >> b;
    cout << "Hello World from C++.Values are:" << a << " " << b;
    return 0;
}

Java程序:

class HelloWorld {
    public static void main(String args[])
    {
        System.out.print("Hello World from Java.");
    }
}
执行上述程序的Python 3 代码:
# Python 3 program to demonstrate subprocess 
# module
  
import subprocess
import os
  
def excuteC():
  
    # store the return code of the c program(return 0)
    # and display the output
    s = subprocess.check_call("gcc HelloWorld.c -o out1;./out1", shell = True)
    print(", return code", s)
  
def executeCpp():
  
    # create a pipe to a child process
    data, temp = os.pipe()
  
    # write to STDIN as a byte object(convert string
    # to bytes with encoding utf8)
    os.write(temp, bytes("5 10\n", "utf-8"));
    os.close(temp)
  
    # store output of the program as a byte string in s
    s = subprocess.check_output("g++ HelloWorld.cpp -o out2;./out2", stdin = data, shell = True)
  
    # decode s to a normal string
    print(s.decode("utf-8"))
  
def executeJava():
  
    # store the output of
    # the java program
    s = subprocess.check_output("javac HelloWorld.java;java HelloWorld", shell = True)
    print(s.decode("utf-8"))
  
  
# Driver function
if __name__=="__main__":
    excuteC()    
    executeCpp()
    executeJava()

输出:

Hello World from C, return code 0
Hello World from C++. Values are:5 10
Hello World from Java.

注意:虽然 subprocess 模块独立于操作系统,但这些命令只能在 Linux 环境中执行。同样根据Python文档,如果与不受信任的输入相结合,传递 shell=True 可能会造成安全隐患。