newbie
wes weston
wweston at att.net
Thu Aug 19 11:46:12 EDT 2004
JASON JESSO wrote:
> I'm trying to add a mode to a mkdir program a got off
> the python cookbook.
>
> The error I get is:
> ./mkdir.py jason 0777
> Traceback (most recent call last):
> File "./mkdir.py", line 31, in ?
> _mkdir( sys.argv[1], sys.argv[2] )
> File "./mkdir.py", line 25, in _mkdir
> os.mkdir( newdir, mode )
> TypeError: an integer is required
>
> When I convert the mode from a string to an octal with
> oct(int(sys.argv[2])) the permissions are all screwed
> up.
>
> Any help?
>
> #!/usr/bin/env python
>
> import sys, os
>
> def _mkdir( newdir, mode ):
> """works the way a good mkdir should :)
> - already exists, silently complete
> - regular file in the way, raise an exception
> - parent directory(ies) does not exist, make
> them as well
> """
> if os.path.isdir( newdir ):
> pass
> elif os.path.isfile( newdir ):
> raise OSError("a file with the same name as
> the desired " \
> "dir, '%s', already exists." %
> newdir)
> else:
> head, tail = os.path.split( newdir )
> if head and not os.path.isdir( head ):
> _mkdir( head, mode )
>
> if tail:
> if mode is None:
> os.mkdir( newdir )
> else:
> os.mkdir( newdir, mode )
>
> if __name__ == '__main__' :
> if len(sys.argv) < 3:
> _mkdir( sys.argv[1], None )
> else:
> _mkdir( sys.argv[1], sys.argv[2] )
>
jason,
Your first instinct in direct problems like this
should be to get in the python interactive interpreter
and play around.
Python 2.3.3 (#1, Mar 11 2004, 22:02:41)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-20)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> perm = "0777"
>>> oct(int(perm))
'01411'
>>>
Note you still need to import.
>>> print math.pi
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'math' is not defined
>>> import math
>>> print math.pi
3.14159265359
>>>
wes
More information about the Python-list
mailing list