用python命令行参数设置c程序输出变量

2024-05-13 20:31:40 发布

您现在位置: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。我的目标是在运行嵌入了c程序(test.c或a.out)的python程序时有一个输出,即输出:

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

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


Tags: 命令行test程序脚本cmdincludeisout
1条回答
网友
1楼 · 发布于 2024-05-13 20:31:40

根据[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.

为了让事情顺利进行:

  • 使用检查输出
  • 使要携带的命令成为列表(而不是字符串)
  • 不通过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()

相关问题 更多 >