将Python输入输出到C程序中

时间:2016-09-05 16:40:13

标签: python terminal pipe

有可能这样做吗?输出Python作为C程序的输入。

如果我之前说这段代码有用,你相信我吗? 现在它不起作用。我怎样才能使它发挥作用?

python -c 'print "a" ' | ./myProgram

myProgram的简单示例:

#include <stdio.h>

int main(int argc, char *argv[]){

  int i = 0;

  if(argc > 0){
    for(i; i<argc; i++){
      printf("%s\n", argv[i]);
    }
    printf("Done.");
  }
  return 0;
}

2 个答案:

答案 0 :(得分:1)

C代码的输入应由scanf

执行

C代码:[test.c]

#include <stdio.h>
int main() {
    int x;
    scanf("%d",&x);
    printf("Value is %d\n",x);
}

编译:

gcc test.c -o foo

Python代码:[test.py]

print (3)

命令:

python test.py | ./foo

输出:

Value is 3

此处C code的标准输入从keyboard更改为管道末尾。 python code的标准输出已从monitor更改为beginning of pipe

C中,有内核级调用来执行此操作。阅读close()dup()来电。我希望你的概念能够被清除。祝你好运:)

您实际上是在尝试打印命令行参数。但看看你的命令。您没有将任何参数传递给myprogram。所以,argc = 0

答案 1 :(得分:0)

这样做是为了让它发挥作用:

$sites = ['https://stackoverflow.com','http://example.org'];
$result = [];
foreach ($sites as $site) {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $site);

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "PHP Curl");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // execute the given URL, and return output
    $result[] = curl_exec($ch);

    curl_close($ch);


}

var_dump($result);

这适用于argc / argv。就像Parnab说的那样,之前没有给出任何论据,因为管道通过./myProgram `python -c 'print "a" '` 来代替