Home > Mobile >  Dealing with compatibility / errors in running Python2.7 script that has leading zeros on unix serve
Dealing with compatibility / errors in running Python2.7 script that has leading zeros on unix serve

Time:07-03

I am trying to get an old Python script running that interacts with a lot of scripts all written in Python 2.7 ... upgrading it all is absolutely not happening, so I need to get around an error.

One module (reply.py) called by the main script (listener.py) has some time parameters in it, with leading zeros, which I presume are causing this error:

[myuser@server ~]$ python2.7 /home/myuser/public_html/app_project/listener.py
Traceback (most recent call last):
  File "/home/myuser/public_html/app_project/listener.py", line 10, in <module>
    from modules import reply
  File "/home/myuser/public_html/app_project/modules/reply.py", line 144
    if now_time >= time(09,00) and now_time <= time(17,00):
                         ^
SyntaxError: invalid token
[myuser@server ~]$ python2.7 /home/myuser/public_html/app_project/listener.py
Traceback (most recent call last):
  File "/home/myuser/public_html/app_project/listener.py", line 10, in <module>
    from modules import reply
  File "/home/myuser/public_html/app_project/modules/reply.py", line 144
    if now_time >= time(09,00) and now_time <= time(17,00):

But the thing I am confused about, is that the main script is set to execute in Python2.7 ... which should be fine with the leading zeros?

The workflow is...

cronjob calls shell script to check python process (listener.py) is running:

#!/bin/bash
pid_file='/home/myuser/public_html/app_project/listener.pid'
if [ ! -s "$pid_file" ] || ! kill -0 $(cat $pid_file) > /dev/null 2>&1; then
  echo $$ > "$pid_file"
  exec /usr/bin/python2.7 /home/myuser/public_html/app_project/listener.py
fi

So the main executable (listener.py) is run in Python2.7 ... so I don't understand what the issue with leading zeroes is in the module (reply.py)...?

Is it because the module (reply.py) is executing via Python3 somehow? Is that why it doesn't like the leading zeros? Or is the 'invalid token' error about something else?

Any advice to get around this would be very much appreciated.

Please note, I do not want to change code extensively (this is not the only piece of code in the app that would have to change, i.e. getting rid of leading zeros and upgrading it to Python3 would take a long, long time to do right), I just want to ensure it all executes fine in 2.7. There are no reasons otherwise to upgrade the app to Python3.

CodePudding user response:

Prior to Python 3, a leading zero for an integer token indicated that the value was octal - e.g., 07. The leading zero alone was an indicator that what followed was octal

In Python 3, leading zeroes can be used for octal values but you need an additional qualifier - e.g., 0o7

A token of 09 would not be valid in either Python 2 or 3

  • Related