|
3 | 3 | from sphinx.util._lines import parse_line_num_spec |
4 | 4 | from docutils import nodes |
5 | 5 | import subprocess |
| 6 | +import hashlib |
| 7 | +import os |
6 | 8 |
|
7 | 9 |
|
8 | 10 | comp_error = ["<ERROR>","Error","app/main.f90","<h1>Bad Request</h1>"] |
9 | 11 |
|
10 | 12 |
|
11 | 13 | class PlayCodeBlock(CodeBlock): |
12 | 14 |
|
13 | | - def compile_and_execute_fortran(self,fortran_code, filename="code.f90"): |
| 15 | + def compile_and_execute_fortran(self,fortran_code): |
| 16 | + code_hash = hashlib.md5(fortran_code.encode('utf-8')).hexdigest() |
| 17 | + cache_filename = f"build/fortran_output_{code_hash}.txt" |
| 18 | + filename=f"build/code_{code_hash}.f90" |
| 19 | + |
| 20 | + # Check if the output is already cached |
| 21 | + if os.path.exists(cache_filename): |
| 22 | + with open(cache_filename, "r") as f: |
| 23 | + return f.read() |
| 24 | + |
14 | 25 | with open(filename, "w") as f: |
15 | 26 | f.write(fortran_code) |
16 | 27 |
|
17 | | - compile_command = ["gfortran", filename] |
| 28 | + compile_command = ["gfortran", filename, "-o", f"./build/{code_hash}.out"] |
18 | 29 | compile_result = subprocess.run(compile_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
19 | 30 |
|
20 | | - if compile_result.returncode == 0: |
21 | | - print("Compilation successful!") |
| 31 | + with open(cache_filename, "w") as f: |
22 | 32 |
|
23 | | - execute_command = ["./a.out"] |
24 | | - execute_result = subprocess.run(execute_command, input="", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
25 | | - |
26 | | - if execute_result.returncode == 0: |
27 | | - print("Execution successful!") |
28 | | - print(execute_result.stdout) |
29 | | - return execute_result.stdout |
| 33 | + if compile_result.returncode == 0: |
| 34 | + print("Compilation successful!") |
| 35 | + |
| 36 | + execute_command = [f"./build/{code_hash}.out"] |
| 37 | + execute_result = subprocess.run(execute_command, input="", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 38 | + |
| 39 | + if execute_result.returncode == 0: |
| 40 | + print("Execution successful!") |
| 41 | + print(execute_result.stdout) |
| 42 | + f.write(str(execute_result.stdout)) |
| 43 | + return execute_result.stdout |
| 44 | + else: |
| 45 | + print("Execution failed.") |
| 46 | + print(execute_result.stderr) |
| 47 | + f.write(str(execute_result.stderr)) |
| 48 | + return execute_result.stderr |
30 | 49 | else: |
31 | | - print("Execution failed.") |
32 | | - print(execute_result.stderr) |
33 | | - return execute_result.stderr |
34 | | - else: |
35 | | - print("Compilation failed.") |
36 | | - print(compile_result.stderr) |
37 | | - return compile_result.stderr |
| 50 | + print("Compilation failed.") |
| 51 | + print(compile_result.stderr) |
| 52 | + f.write(str(compile_result.stderr)) |
| 53 | + return compile_result.stderr |
38 | 54 |
|
39 | 55 | def run(self): |
40 | 56 | document = self.state.document |
|
0 commit comments