Python Forum
code to understand the script execution - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: code to understand the script execution (/thread-7344.html)



code to understand the script execution - Skaperen - Jan-05-2018

i'd like to have a script with a #! in the first line test to see if it was executed by a means that actually used the #! or if a python interpreter was explicitly run and the path to the script was passed to it in the first argument after any preceding options. python tweaks sys.argv so that the interpreter token is removed, making things consistent for the most common cases, but hindering this particular case. anyone have any ideas?


RE: code to understand the script execution - Gribouillis - Jan-05-2018

I don't think it is possible because the shell interpretes the shebang line #! before running the program: it adds the interpreter name in front of the program name. However, the OS knows the whole command line that started the process, and you can cheat by using an unlikely interpreter name in the shebang line. The following example uses module psutil together with this trick to detect if the shebang line was used:
#!/usr/bin/././././python3

import psutil

if __name__ == '__main__':
    proc = psutil.Process()
    cmd = proc.cmdline()
    if cmd[0] == '/usr/bin/././././python3':
        print("This script was probably run from the shebang line.")
    else:
        print("This script was called without shebang line.")



RE: code to understand the script execution - Skaperen - Jan-06-2018

cheating works. i learned this in school.