Skip to content

Instantly share code, notes, and snippets.

@Supm4n
Created March 16, 2020 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Supm4n/1c37feed1d793d6d61ea2abe28138d6a to your computer and use it in GitHub Desktop.
Save Supm4n/1c37feed1d793d6d61ea2abe28138d6a to your computer and use it in GitHub Desktop.
#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