【问题标题】:Python script to test game测试游戏的 Python 脚本
【发布时间】:2014-11-25 18:27:31
【问题描述】:

我编写了一个名为 reversi.py 的游戏,我想为其编写一个脚本来帮助测试。该游戏基于人工智能,需要大量时间才能运行。我希望编写一个脚本来运行游戏并将其结果输出到一个文件中,这样我就可以运行游戏 x 次,同时我去做其他事情并返回它。我一直试图从脚本文件中调用游戏。这是我目前所拥有的:

from games import *
from reversi import *

def main():

    f = open('Reversi Test', 'w')


if __name__ == '__main__':
    main()

提前致谢!

【问题讨论】:

  • 游戏是否已经将结果输出到文件中?
  • 不,它不会,它只是打印到屏幕上。我需要更多关于如何在不同文件中调用函数并编写结果的指导。
  • 打印到屏幕...到终端,还是到 GUI?如果它是一个 GUI(并且你不能修改它),那么你就不走运了。
  • 是的,我指的是终端。对此感到抱歉。
  • 您使用的是什么操作系统?如果它打印到终端,并且您可以访问 bash 终端(例如 Linux、OSX),那么像 run_program > output.txt 这样简单的东西就可以了!

标签: python testing reversi


【解决方案1】:

如果程序写入标准输出,则只需将其重定向到其他文件。类似于以下内容

import sys

from games import *
from reversi import *

def main():

    N = 100
    for i in range(N):
       sys.stdout = open('Reversi_Test_' + str(i), 'w')
       game() # call your method here
       sys.stdout.close()

if __name__ == '__main__':
    main()

您也可以使用with 语句:

from future import with_statement
import sys

from games import *
from reversi import *

def main():

    N = 100
    for i in range(N):
       with open('Reversi_Test_' + str(i), 'w') as sys.stdout:
           game() # call your method here

if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2017-01-26
    • 2021-04-14
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多