argv[0] manipulation
Bengt Richter
bokr at oz.net
Wed Dec 11 13:46:19 EST 2002
On Wed, 11 Dec 2002 12:02:52 +0000, P_spam_ at draigBrady.com wrote:
>Hi,
>
>I had the idea to select debugging mode
>in my application depending on the contents of argv[0].
>The logic was:
>
> if '/' in argv[0]: #explicit path so debug
> debugging = 1
> else:
> debugging = 0
>
What's wrong with the typical option usage of -d or --debug or whatever suits you?
E.g.,
--< tdeb.py >--
def test(opt_debug, args):
print 'Debugging is %s' % ['off','on'][not not opt_debug]
print 'Args are:', args
if __name__ == '__main__':
import sys
args = sys.argv[1:]
opt_debug = args and args[0].lower() in ['-d','--debug']
if opt_debug:
args.pop(0) # remove the opt arg
test(opt_debug, args)
---------------
[10:42] C:\pywk\clp>tdeb.py
Debugging is off
Args are: []
[10:42] C:\pywk\clp>tdeb.py -d
Debugging is on
Args are: []
[10:42] C:\pywk\clp>tdeb.py --debug and some args
Debugging is on
Args are: ['and', 'some', 'args']
[10:43] C:\pywk\clp>tdeb.py and some args
Debugging is off
Args are: ['and', 'some', 'args']
Or you could mess with sys.argv itself and set a global debug flag, or whatever,
but a trick with argv[0] seems cryptic and unnecessary. Or am I missing something?
(OTOH, if you are on unix, you could easily give your app a totally different name
as a symlink that should show up in argv[0] and then check the name, like vi vs view etc).
Regards,
Bengt Richter
More information about the Python-list
mailing list