小能豆

Unknown Syntax Error in Python

javascript

I’m very new to python and I’m trying to import a script so I can run it and I’m kind of barred off right out the gate. I’m uncertain where the invalid syntax is and how to fix it.

Traceback (most recent call last):
** IDLE Internal Exception: 
  File "C:\Python34\lib\idlelib\run.py", line 353, in runcode
    exec(code, self.locals)
  File "C:\Users\Admin\Desktop\hangouts\run.py", line 1, in <module>
    import hangouts.py
  File "C:\Users\Admin\Desktop\hangouts\hangouts.py", line 380
    print "[%s] %s" % (os.path.basename(__file__), unicode(message).encode('utf8'))
                  ^
SyntaxError: invalid syntax

阅读 81

收藏
2023-11-26

共1个答案

小能豆

The error you’re encountering is due to the use of Python 2 syntax for the print statement in a script that is being run in Python 3. In Python 3, print is a function and should be called with parentheses.

Here’s the relevant line causing the issue:

print "[%s] %s" % (os.path.basename(__file__), unicode(message).encode('utf8'))

You can modify it to use the correct syntax for Python 3:

print("[%s] %s" % (os.path.basename(__file__), str(message).encode('utf8')))

In this modified version, I changed print to a function by adding parentheses, and I replaced unicode with str because unicode is specific to Python 2, and in Python 3, you can use str for the same purpose.

If you’re working with Python 3.6 or later, you can use f-strings for a more concise and readable syntax:

print(f"[{os.path.basename(__file__)}] {str(message).encode('utf8')}")

This way, you don’t need the % formatting, and you can directly include expressions inside the string using curly braces {}.

2023-11-26