如何通过Python脚本多次运行相同程序并使用不同输入?

2 投票
4 回答
2508 浏览
提问于 2025-04-17 20:58

我需要运行一个简单的C程序好几次,每次用不同的输入字符串(比如说是AAAAA...,逐渐增加长度,直到输出“TRUE”)。

例如:

./program A # output FALSE
./program AA # output FALSE
./program AAA # output FALSE
./program AAAA # output FALSE
./program AAAAA # output FALSE
./program AAAAAA # output FALSE
./program AAAAAAA  # output TRUE

在C语言中,我可以简单地使用一个while循环。我知道在Python中也有while循环。

所以Python程序会是:

strlen = 0
while TRUE
 strlen++
 <run ./**C program** "A"*strlen > 
 if (<program_output> = TRUE)
   break

假设我可以通过写下面的代码来让.py脚本可以执行:

#! /usr/bin/env python

还有

 chmod +x file.py

我该怎么做才能让这个工作呢?

提前谢谢你!

4 个回答

1

使用 commands。这里有相关的文档 http://docs.python.org/2/library/commands.html

  1. commands.getstatusoutput 可以获取你 C 程序的标准输出(stdout)。也就是说,如果你的程序有输出内容,可以用这个方法来获取。(实际上,它返回的是一个元组 (0, out),其中包含了标准输出的内容)。
  2. commands.getstatus 会返回程序的布尔状态,你也可以用这个。

所以,假设你是用标准输出去捕获 ./program 的输出,整个修改后的程序看起来是这样的:

import commands

while TRUE:
  strlen += 1
  output = commands.getstatusoutput("./program " + "A"*strlen)
  outstatus = output[1]
  if output == "true":
     break

我会尝试使用 getstatus 来看看能否读取 program 返回的值。

补充:我没注意到 commands 从 2.6 版本开始就不推荐使用了,请使用 subprocess,具体可以参考其他的回答。

1

file.py

import os

count=10
input="A"
for i in range(0, count):
    input_args=input_args+input_args
    os.popen("./program "+input_args)

运行file.py这个文件会让./program这个程序执行10次,每次的输入参数A都会逐渐增大。

4

你可以使用 subprocess.check_output 这个功能:

import subprocess
strlen = 0
while True:
    strlen += 1
    if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE':
        break
2

你可以试试这样的做法(具体可以参考文档):

import subprocess

args = ""
while True:
     args += "A"
     result = subprocess.call(["./program", "{args}".format(args=args)])
     if result == 'TRUE':
         break

这里推荐使用subprocess模块,而不是os.popen命令,因为后者从2.6版本开始就不再推荐使用了。详细信息可以查看os文档

撰写回答