【问题标题】:setting variable to output of c program with command line arguments in python在python中使用命令行参数将变量设置为c程序的输出
【发布时间】:2019-11-04 17:57:58
【问题描述】:

我正在尝试使用 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 c subprocess command-line-arguments


【解决方案1】:

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

运行 args 描述的命令。等待命令完成,然后返回returncode 属性

为了让事情顺利进行:

  • 改用 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()

【讨论】:

  • 我尝试了你的建议,现在我得到了这个错误: Traceback (last recent call last): File "cleanita.py", line 6, in parm31=subprocess.check_output(cmd)文件“/usr/lib64/python2.7/subprocess.py”,第 568 行,在 check_output
  • 还有:process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib64/python2.7/subprocess.py", line 711, in init errread, errwrite) 文件“/usr/lib64/python2.7/subprocess.py”,第 1327 行,在 _execute_child raise child_exception OSError: [Errno 2] No such file or directory 我该如何解决这个问题? ?
  • 我对代码添加了一个小修正。根据您的错误,您正在执行的不是我的复制/粘贴代码。如果错误仍然存​​在,请添加您分配给 cmd 的值。让我知道结果如何。
  • @jms1980:这回答了你的问题吗?如果是,请接受答案,以便其他人也能承认([SO]: What should I do when someone answers my question?)。
猜你喜欢
  • 2014-05-26
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2013-08-02
  • 2022-01-24
  • 2013-02-03
  • 2012-08-30
  • 1970-01-01
相关资源
最近更新 更多