Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an octal value in Python 2 & 3

Tags:

python

I need to write 0644 (0o644) in Python 2 and 3 compatible way. How to do it? The only ideas I have is to parse this from string or convert into hex or decimal. That's not human-readable. I don't mind slow speed, it's called just once.

like image 871
lzap Avatar asked May 15 '18 08:05

lzap


Video Answer


2 Answers

Very old python 2 versions (< 2.6) don't accept the octal prefix in 0o644.

If you really need to be compliant with python 2.5 or earlier you can parse an octal string with int

int('644',8)

note that compatibility tricks catching ImportError, NameError, ... exceptions don't work here because you cannot catch the SyntaxError, the parser doesn't let that happen:

# that doesn't work
try:
    x = 0644   # either crashes here
except SyntaxError:
    x = 0o644  # or here
# that doesn't work
like image 156
Jean-François Fabre Avatar answered Oct 25 '22 17:10

Jean-François Fabre


0o644 is compatible with both python2 and python3

like image 24
enrico.bacis Avatar answered Oct 25 '22 17:10

enrico.bacis