Created
March 16, 2020 03:06
-
-
Save Supm4n/1c37feed1d793d6d61ea2abe28138d6a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#In Python3.x this is the closest thing I could come up with to executing a file directly, that matches running python /path/to/somefile.py. | |
#Notes: | |
#Uses binary reading to avoid encoding issues | |
#Garenteed to close the file (Python3.x warns about this) | |
#defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__" | |
#setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them. | |
def exec_full(filepath): | |
import os | |
global_namespace = { | |
"__file__": filepath, | |
"__name__": "__main__", | |
} | |
with open(filepath, 'rb') as file: | |
exec(compile(file.read(), filepath, 'exec'), global_namespace) | |
# execute the file | |
exec_full("/path/to/somefile.py") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment