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

标签 python c subprocess command-line-arguments

我正在尝试使用一个 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()

关于python - 在python中使用命令行参数将变量设置为c程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710955/

相关文章:

python - 如何在 GPU 上有效并行化 AlphaZero?

python - sleep 无法在需要的地方发挥作用

c - 在 while 循环中使用 scanf 函数

python - 在子进程命令中传递用双引号引起来的参数

python - 为什么 shell=True 会吃掉我的 subprocess.Popen stdout?

python - 使用子进程执行的子 Python 没有输出

python - 尝试为 python 3.7 安装 pillow 5.3.0 时出现问题

python - 按小时过滤 DataFrame 行

c - 为什么提示我输入的次数比我预期的要多?

c - 在 C 中,使用同一结构内的另一个值设置结构内数组的大小