编程语言调用命令行操作

写在前面

使用语言

  • Python
  • C

可执行文件hello.sh:

#!/bin/bash
echo "hello my friend"

不要忘记赋予hello.sh执行权限

Python

Python文件

import os
os.system("./hello.sh")
os.system("echo %s" % ('hello'))

结果:

hello my friend
hello

C

使用C库函数 int system(const char *command)

C文件

#include <stdlib.h>

int main(int argc, char *argv[]){
  system("./hello.sh");
  return 0;
}

结果:

hello my friend

Java

Java文件

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Test{
  public static void main(String[] args){
    try{
      String cmd = "./hello.sh";
      Process process = Runtime.getRuntime().exec(cmd);
      BufferedReader buffered = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line;
      while((line = buffered.readLine()) != null) {
        System.out.println(line);
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

结果

hello my friend

comment: