python - 文件复制到 tempfile.TemporaryDirectory 找不到?
问题描述
我期待以包含脚本(例如,solution.py
或solution.js
)的目录形式收到一些带回家作业的解决方案,当在同一目录中运行时(使用python solution.py
或node 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()
什么吗?为什么找不到输入文件?
解决方案
要将Thierry Lathuille的评论转换为答案,我先做os.chdir(tempdir)
然后简单地运行来让它工作subprocess.run(["python3", "solution.py"])
。
推荐阅读
- flutter - 即使应用程序已被终止,也显示 Flutter 通知
- python - 模型运行问题由于“来自 keras.applications 导入 Xception
- go - proto UnmarshalText 在未知字段上失败
- batch-file - 如果多次选择批处理脚本,则删除选项
- node.js - 如何根据现有数据有条件地更新猫鼬中的文档?
- c# - 获取“Form1”的“部分声明”不得指定不同的基类
- pine-script - 获取一段时间内移动平均线交叉的总数,并在它出现的区域上绘制一个标签
- deap - 当 max_ 参数大于 1 并且无法生成程序时,Minimal DEAP 脚本会引发令人困惑的异常
- mysql - 删除不必要的 wordpress 用户元数据是否安全?
- amazon-web-services - 使用别名访问 KMS 加密存储桶