首页 > 解决方案 > 文件复制到 tempfile.TemporaryDirectory 找不到?

问题描述

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

我想为这些目录编写“单元测试”,以便它们有效地运行不同的输入(input1.txt、、input2.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在其中看到一个:

在此处输入图像描述

'有效'sys.path不是在打开文件之前存在的那个吗?我必须做些os.chdir()什么吗?为什么找不到输入文件?

标签: python

解决方案


要将Thierry Lathuille的评论转换为答案,我先做os.chdir(tempdir)然后简单地运行来让它工作subprocess.run(["python3", "solution.py"])


推荐阅读