c++ - c 或 c++ 中是否有类似 subprocess.getoutput() 的函数或方法?

标签 c++ c python-3.x

Python:

print("Active Device:"+subprocess.getoutput("ip link|grep \"state UP\"|cut -d : -f 2|cut -d \' \' -f2"))

我可以通过这样做在c中得到像That⬆这样的输出吗?: C:

printf("Active Device:%s",getsystemoutput("ip link|grep \"state UP\"|cut -d : -f 2|cut -d \' \' -f2"));

最佳答案

函数 getsystemoutput() 可能如下所示:

char *getsystemoutput( char *cmd )
{
    static char output[1024];

    FILE *fp;

    if( (fp = popen( cmd, "r" )) == NULL )
        return "";

    if( fgets( outout, sizeof output, fp ) == NULL )
        strcpy( output, "" );

    pclose( fp );
    return output;
}

此版本在出现错误时返回一个空字符串,并使用静态缓冲区进行输出,这使得在 printf() 中使用变得很容易,但出于一般目的,我建议在错误并传递 output + 它的大小作为参数。您可能还想检查 pclose() 的结果以确定所调用命令的退出状态。请注意,如果没有循环,它只会返回第一行输出。

关于c++ - c 或 c++ 中是否有类似 subprocess.getoutput() 的函数或方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909072/

相关文章:

c++ - 来自 std::find 的此错误的优雅解决方案是什么?

c - 在声明 VLA 的同一序列点中启动 VLA 的大小部分是否有效?

python-3.x - numpy 结构化数组没有形状信息?

c - GDB 为数组值返回<optimized out>

python - 按下按钮时的PyAudio记录

python-3.x - PyQt5 stub 文件

c# - 在 Windows 系统上注销用户后立即让系统进入休眠状态

C++ 友元函数不工作(有多个头文件和源文件)

c++ - C++ 中表达式必须具有常量值

在 C 中通过混合 char[] 和 int 创建字符串