Why my code is working in python2 and not in python3

Viewed 339
import os
import time

CONSOLE = "/dev/tty0"
logfd = None
def log_me(logstr):
    global logfd
    global CONSOLE

    print(time.strftime("%c")+": "+logstr)
    if not logfd:
        if not os.path.exists(CONSOLE):
            return
        logfd = open(CONSOLE, "a")
        if not logfd:
            return

    logfd.write(logstr+"\n")
    logfd.flush()

    return

test.py

from consolelog import log_me

print ("Hello World!")
log_me("This is a Hello World script")
log_me("Logging 2nd time to see how it works.")
log_me("loging 3rd time")

The same code is working when used with python2 but throwing error 29 illegal seek when run with python3

[root@869ebe33-77e8-41b4-918b-eafda978fd98 ~]# python test.py
Hello World!
Wed Apr 14 07:37:03 2021: This is a Hello World script
Wed Apr 14 07:37:03 2021: Logging 2nd time to see how it works.
Wed Apr 14 07:37:03 2021: loging 3rd time

output with python3

[root@869ebe33-77e8-41b4-918b-eafda978fd98 ~]# python3 test.py
Hello World!
Wed Apr 14 07:37:10 2021: This is a Hello World script
Traceback (most recent call last):
File "test.py", line 4, in
log_me("This is a Hello World script")
File "/root/consolelog.py", line 14, in log_me
logfd = open(CONSOLE, "a")
OSError: [Errno 29] Illegal seek

1 Answers

with python3.x append doesn't work with open(/dev/tty0) so we have to use write instead of append.

Related