在 python 中使用命令行参数将变量设置为 c 程序的输出

setting variable to output of c program with command line arguments in python

我正在尝试使用 python 脚本,其中一个变量设置为需要命令行参数的 c 程序 test.c 的输出。下面是我的c程序:

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

int main(int argc, char *argv[])
{
       int lat;
       lat=atoi(argv[1]);
       printf("-->%d\n",lat);
}

python程序是:

  import subprocess

  for lat in range(80,-79,-1):
           cmd = '"./a.out" {}'.format(lat)
           print "cmd is ",cmd
           parm31=subprocess.call(cmd,shell=True)
           print "parm is ",parm31

我编译了test.c得到a.out。我的目标是当 运行 嵌入了 c 程序(test.c 或 a.out)的 python 程序输出为:

 parm is -->80
 parm is -->79
 parm is -->78
 ...
 parm is -->-77
 parm is -->-78

不幸的是,我没有得到输出,而是变量的数字分量的其他值和一些其他不需要的输出。我该如何调整这个程序以获得正确的输出?

根据[Python 2.Docs]: subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)强调是我的):

Run the command described by args. Wait for command to complete, then return the returncode attribute.

要使事情正常进行:

  • 改用check_output
  • 将要携带的命令设为列表(不是字符串)
  • 不及格shell=True
import subprocess

for lat in range(80, -79, -1):
    cmd = ["\"./a.out\"", "{}".format(lat)]
    print "Command is ", " ".join(cmd)
    out = subprocess.check_output(cmd)
    print "Command output is ", out.strip()