简体   繁体   English

从 python 运行另一个 python 程序

[英]Running another python program from python

I am trying to build a test script to test my python code.我正在尝试构建一个测试脚本来测试我的 python 代码。

The tested code should read from stdin and write to stdout.测试代码应该从标准输入读取并写入标准输出。

The tester code should call the tested code passing the values in a file as stdin, and read stdout to compare with the expected values (stored in another file)测试器代码应该调用测试代码将文件中的值作为标准输入传递,并读取标准输出以与预期值进行比较(存储在另一个文件中)

Tested code:测试代码:

n = int(input())
x1,y1 = list(map(int, input().rstrip().split())) 
x2,y2 = list(map(int, input().rstrip().split())) 

#what it does is really not importante
if ((min(x1, x2) <= n/2) and (max(x1, x2) > n/2) or
    (min(y1, y2) <= n/2) and (max(y1, y2) > n/2)):
    print('S')
else :
    print ('N')

Tester code:测试代码:

import os
import subprocess as sp
inputs = os.listdir("./warmup_tests/warmup_B/input")
for ipt in inputs:
    with open('./warmup_tests/warmup_B/input/{}'.format(ipt)) as f:
        res = (sp.run(['python', 'b.py'], stdin=f, capture_output=True))

I have received multiple of the following error (when disabling capture_output to better visualization):我收到了多个以下错误(禁用 capture_output 以更好地可视化时):

Traceback (most recent call last):
  File "b.py", line 10, in <module>
    x1,y1 = list(map(int, input().rstrip().split())) 
  File "<string>", line 1
    5 2
      ^
SyntaxError: unexpected EOF while parsing

My input file is the following:我的输入文件如下:

10
5 2
5 1

The above works when there is only one input() on the tested code.当测试代码上只有一个input()时,上述方法有效。 What am I missing for making it work with multiple input() ?使它与多个input()一起工作我缺少什么?

Your code is work for me (with small changes).您的代码对我有用(稍作改动)。 It works and with capture_output=True , and with capture_output=False它适用于capture_output=Truecapture_output=False

https://drive.google.com/open?id=16NK1_Qfdd98prpmBUqaP894j8uGTNdnf https://drive.google.com/open?id=16NK1_Qfdd98prpmBUqaP894j8uGTNdnf

command to run:运行命令:

python3 tester.py

For your problem: I suspect in your input files can missing '\n' in some lines (may be editor bug, don't know).对于您的问题:我怀疑您的输入文件中的某些行可能缺少 '\n' (可能是编辑器错误,不知道)。

Also try check indents in your module b.py还可以尝试检查模块b.py中的缩进

Can you share your code with input files for detailed analysing?您可以与输入文件共享您的代码以进行详细分析吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM