C語言與python獲取命令行輸出

這個是我在網上看到的代碼,自己編譯運行了一下,可以通過

#include<stdlib.h>
#include<stdio.h>


void execSysCommand(char *command/* in */,char* res/* out */)
{
    char buff[128] = {0};
    FILE *file = NULL;
    file = popen(command,"r");   //打開一個管道流判斷是否可以使用

    if(file == NULL)
    {
       return;
    }
    while(!feof(file))
    {
       if(fgets(buff,128,file))
       {
          strcat(res,buff);
       }

    }
    pclose(file);
}

int main(int argc,char *argv[])
{
   char res[1024] ={0};
   execSysCommand("pwd",res);
   printf("%s",res);
   return 0;
}

Python中也有一些可以這樣運行的代碼
我們可以使用

os.system('pwd')//打印當前路徑

運行結果:第一個中我們執行會有狀態碼
這裏寫圖片描述
這裏寫圖片描述

利用管道的方式

os.popen('pwd').readlines() //打開管道執行pwd命令

這裏寫圖片描述
我們也可以使用命令

commands.getoutput('pwd')  //命令獲取輸出

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章