我想知道如何在c中通过管道输出stdout。这是从Linux传递命令'ls'的stdout并将其存储在变量中,然后输出变量值的示例:
import subprocess
#Piping stdout of the command 'ls' from linux
test = subprocess.Popen("ls", stdout = subprocess.PIPE)
stdoutpiped = test.stdout.read().decode('utf-8')
print(stdoutpiped)
运行代码的结果:
Destkop
Documents
Images
Videos
Downloads
MyCodes
passwords.txt
您将如何在c
中执行此操作?
谢谢!
答案 0 :(得分:0)
您可以使用popen尝试以下操作:
#include <stdio.h>
#define PATH_MAX 1000
int main( ) {
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
printf("Error, reported");
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
printf("Done running");
}
return 0;
}
您会找到更多信息here。