3

ここに似たような質問があることは知っていますが、別の問題があります。

I have some code files in a plugin but the plugin uses internal paths only the software knows, so I am not able to access that path to use it with execfile.

But there is an internal python function called readInternalFile (path), where I can use this internal path and it returns the contents of this file as a string.

So I thought then I could use the standard python function exec, but as soon as I do that, it complains about the very first line being '\r\n'.

How can I fix this? I print the type of the data readInternalFile returns, and it's str, so everything should be fine, right?

The code in the file works by itself and has no syntax errors, etc.

4

1 に答える 1

0
s1 = readInternalFile(path)
statements = s1.split("\r\n")
for stmt in statements:
    exec(stmt)

動作するはずです

>>> s1 = "a=32\r\nb=a+5\r\nprint b"
>>> statements = s1.split("\r\n")
>>> for stmt in statements:
...    exec(stmt)
...
37
>>>

または、エンドラインを「;」に置き換えることもできます。そのようです

>>> s1 = "a=32\r\nb=a+5\r\nprint b"
>>> s2 = s1.replace("\r\n",";")
>>> exec(s2)
37

また、通常execを使用することは悪い考えです...

また、エンドラインエンコーディングを切り替えると、これは機能しなくなります。

于 2012-07-27T21:02:47.960 に答える