bartolomeo
bartolomeo

Reputation: 11

Syntax error RunPython using xlwings, sys.path

OS Windows 10 Pro

Versions of xlwings, Excel, and Python (0.9.0, Office 365, Python 3.8.2)

I am new on using xlwings through VBA. I run the exact syntax from a tutorial webpage on both VBA and Python, but it gives error like this:

  File "<string>", line 1

    import sys, os; sys.path[0:0]=os.path.normcase(os.path.expandvars(r'C:\Users\User\Trial2;C:\Users\User\Trial2\Trial2.zip;C:\Users\User\Anaconda3\')).split(';'); import Trial2;Trial2.main()                                                                                                                                                               

SyntaxError: invalid syntax

I used original syntax for VBA, and the syntax I used for python is like this:

import xlwings as xw


#@xw.sub  # only required if you want to import it or run it via UDF Server
def main():
    wb = xw.Book.caller()
    wb.sheets[0].range("A1").value = "Hello xlwings!"


#@xw.func
def hello(name):
    return "hello {0}".format(name)


if __name__ == "__main__":
    xw.Book("Trial2.xlsm").set_mock_caller()
    main()

I barely find any clue for this problem, so I'm hoping that someone can give me a solution

Upvotes: 1

Views: 2029

Answers (2)

Tj Buttrick
Tj Buttrick

Reputation: 11

I realize this is a long time after the initial question but I had the same issue and couldn't find an answer anywhere. After playing around (for much longer than I care to admit) I found the problem for me was that my .xlsm/.py file names contained a space. With no other changes, everything worked when I replaced the space with an underscore.

Upvotes: 1

tdelaney
tdelaney

Reputation: 77367

This is a quirk in python's string literals. Even with raw strings the backslash escapes the quote character so r"ends in quote\"" is valid. It also means that raw strings can't end in a single backslash. r"ends in slash\" is a syntax error. If you need to end a string with a backslash, you can't use raw. "ends in slash\\" is okay.

I'm not sure where the failing string comes from, but you need to change it to

import sys, os; sys.path[0:0]=os.path.normcase(os.path.expandvars('C:\\Users\\User\\Trial2;C:\\Users\\User\\Trial2\\Trial2.zip;C:\\Users\\User\\Anaconda3\\')).split(';'); import Trial2;Trial2.main()

See Python Lexical Analysis

Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character).

Upvotes: 0

Related Questions