This is a complete hack, but it works for your given example. The downside is that its wrapping the last line of the code to be executed into a print()
function, so if the target routine actually has a print statement last, you're going to get a None
as output:
#show_the_latest.py
import sys
import subprocess
try:
target = sys.argv[1]
except IndexError:
print("Target routine was not passed in")
sys.exit()
with open(target) as program:
code = [line.strip() for line in program.readlines() if line.strip() != ""]
if code:
code[-1] = f"print({code[-1]})"
to_execute = ["python", "-c", "; ".join(code)]
subprocess.Popen(to_execute)
code.py
x = 1
y = 2
x+y
Then python show_the_latest.py code.py
will output 3
Note that this is definitely not completely robust, and there should probably be a more complete line validation check within the list comprehension that is building the code to be executed. For example, in its current form, if any line contains a comment #
, then nothing after that will be executed, because the -c
modifier of the python executable will consider everything after the # to be part of the comment. The check I did include will make sure that blank lines don't result in a syntax error.