How to test a Python script with an input file fil

2019-02-28 00:28发布

I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?

标签: python input
4条回答
We Are One
2楼-- · 2019-02-28 01:12

Read from file(s) and/or stdin:

import fileinput
for line in fileinput.input():
    process(line)
查看更多
趁早两清
3楼-- · 2019-02-28 01:19

So the script normally takes test cases from stdin, and now you want to test using test cases from a file?

If that is the case, use the < redirection operation on the cmd line:

my_script < testcases.in
查看更多
爷的心禁止访问
4楼-- · 2019-02-28 01:19

PyUnit "the standard unit testing framework for Python" might be what you are looking for.


Doing a small script that does something like this:

#!/usr/bin/env python
import sys

def main():
    in_file = open('path_to_file')
    for line in in_file:
        sys.stdout.write(line)

if __name__ == "__main__":
    main()

And run as

this_script.py | your_app.py
查看更多
不美不萌又怎样
5楼-- · 2019-02-28 01:23

You can do this in a separate file.

testmyscript.py

import sys
someFile= open( "somefile.in", "r" )
sys.stdin= someFile
execfile( "yourscript.py" )
查看更多
登录 后发表回答