找不到复制到tempfile.TemporaryDirectory的文件吗?

时间:2018-08-12 18:35:06

标签: python

我期望以包含脚本(例如solution.pysolution.js)的目录的形式收到一些带回家作业的解决方案,这些脚本在同一目录中运行时(带有python solution.pynode solution.js)将读取该目录中的input.txt并产生一个output.json

我想为此类目录编写“单元测试”,以使它们有效地运行不同的输入(input1.txtinput2.txt等)。我的方法是创建一个临时目录,将解决方案脚本复制到其中,复制相关的输入文件(重命名为input.txt),然后在该临时目录中运行该脚本。到目前为止,这是我尝试过的:

import tempfile
import os
import shutil
import argparse
import subprocess
import time

# Name of the input and output file
INPUT_FILE = 'input.txt'
OUTPUT_FILE = 'output.json'

parser = argparse.ArgumentParser(
        description="Run take-home assignment test script")
parser.add_argument('solutiondir')


def run_test(solutiondir, inputfile):
    with tempfile.TemporaryDirectory() as tempdir:
        copy_input_file(inputfile, tempdir)

        maybe_run_python(solutiondir, tempdir)


def copy_input_file(inputfile, tempdir):
    shutil.copyfile(inputfile, os.path.join(tempdir, INPUT_FILE))


def maybe_run_python(solutiondir, tempdir):
    solutionpy = os.path.join(solutiondir, 'solution.py')
    if os.path.isfile(solutionpy):
        print("solution.py found. Running...")
        dst = os.path.join(tempdir, 'solution.py')
        shutil.copyfile(solutionpy, dst)
        tic = time.time()
        completed_process = subprocess.run(["python3", dst])
        toc = time.time()
        print(f"Process completed in {toc - tic}.")


if __name__ == "__main__":
    run_test(
        solutiondir=parser.parse_args().solutiondir,
        inputfile='test/inputs/input1.txt')

这是我的目录结构:

.
├── solutions
│   └── Test
│       └── solution.py
└── test
    ├── inputs
    │   └── input1.txt
    └── run_solution.py

上面的脚本是run_solution.py,我有一个Test/solution.py,其中只包含一行:

open('input.txt')

但是,如果我尝试运行脚本,则会收到未找到input.txt的错误消息:

Kurts-MacBook-Pro:cleo-challenge kurtpeek$ python test/run_solution.py solutions/Test
solution.py found. Running...
Traceback (most recent call last):
  File "/var/folders/0p/jfjngh2x19dfyg2dpxnw7f2h0000gn/T/tmp02q4nmc8/solution.py", line 1, in <module>
    open('input.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'input.txt'
Process completed in 0.02921915054321289.

让我感到困惑的是,如果我在open('input.txt')之前进入调试器,我会看到临时目录位于路径的开头:

Kurts-MacBook-Pro:cleo-challenge kurtpeek$ python test/run_solution.py solutions/Test
solution.py found. Running...
> /var/folders/0p/jfjngh2x19dfyg2dpxnw7f2h0000gn/T/tmpguwf91h7/solution.py(2)<module>()
      1 import ipdb; ipdb.set_trace()
----> 2 open('input.txt')

ipdb> import sys
ipdb> sys.path
['', '/private/var/folders/0p/jfjngh2x19dfyg2dpxnw7f2h0000gn/T/tmpguwf91h7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/IPython/extensions', '/Users/kurtpeek/.ipython']
ipdb> 

此外,如果我打开该目录,则会在其中看到一个input.txt

enter image description here

“有效” sys.path不是刚刚打开文件之前存在的那个吗?我需要做os.chdir()还是其他什么?为什么找不到输入文件?

1 个答案:

答案 0 :(得分:0)

要将Thierry Lathuille的评论转换为答案,我首先通过执行os.chdir(tempdir)然后简单地运行subprocess.run(["python3", "solution.py"])使它起作用。