Created
December 9, 2022 17:15
-
-
Save goretkin/f6d84b2ae824bb17a29455eda4eb1789 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing | |
def functionality(arg1): | |
import sys | |
print("arg1: " + str(arg1)) | |
print("sys.executable: " + str(sys.executable)) | |
print("-----\n") | |
return sys.executable | |
def worker(queue, arg1): | |
import traceback | |
try: | |
retval = functionality(arg1) | |
queue.put({"retval": retval}) | |
except Exception as e: | |
queue.put({"exception": e, "traceback_str": traceback.format_exc()}) | |
raise | |
finally: | |
pass | |
def spawn_worker(arg1): | |
queue = multiprocessing.Queue() | |
p = multiprocessing.Process(target=worker, args=(queue, arg1,)) | |
p.start() | |
p.join() | |
err_or_ret = queue.get() | |
handle_worker_err(err_or_ret) | |
if p.exitcode != 0: | |
raise RuntimeError("Subprocess failed with code " + str(p.exitcode) + ", but no exception was thrown.") | |
return err_or_ret["retval"] | |
def handle_worker_err(err_or_ret): | |
if "retval" in err_or_ret: | |
return None | |
err = err_or_ret | |
#import traceback | |
if (err is not None): | |
#traceback.print_tb(err["traceback"]) # TODO use e.g. tblib to get traceback | |
print("The exception was thrown in the child process, reraised in parent process:") | |
print(err["traceback_str"]) | |
raise err["exception"] | |
def test_exes(): | |
exe1 = functionality("called directly") | |
exe2 = spawn_worker("called via multiprocessing") | |
print("The two exes:") | |
print(exe1) | |
print(exe2) | |
assert exe1 == exe2 | |
if __name__ == "__main__": | |
test_exes() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output of running the script in a version of python that comes with a scriptable application: