How to set program name in Python? ($0 in Perl)

jmdeschamps at gmail.com jmdeschamps at gmail.com
Fri Nov 11 00:29:49 EST 2005


This is not directly what the OP wanted in regards to Perl, but to see
what one could do if one needed to change the name of the running
program, I wrote this:
## START PROGRAM
import sys
import os.path
import shutil
import os

def testChangingName(appname):
    hopedfornameis = appname
    mylongnameis = sys.argv[0]
    mynameis = os.path.basename(mylongnameis)
    basenameis  = os.path.dirname(mylongnameis)
    if  mynameis != hopedfornameis:
        shutil.copyfile(mynameis, basenameis+"/"+hopedfornameis)

os.spawnv(os.P_NOWAIT,"c:/python23/python.exe",('c:/python23/python.exe',hopedfornameis))
        sys.exit()

if __name__ == "__main__":
    print sys.argv[0]
    testChangingName("testNameIsChanged.py")
    s=raw_input("All's well!")
    s=raw_input("Now do something useful")

## END PROGRAM

Since I don't know the circumstance in which the OP wanted to change
the name, I really don't know what caveats one should look out for
here.
I would be curious to know when such a function could come in handy.

Jean-Marc




More information about the Python-list mailing list