如何在没有默认Windows crlf的情况下生成py文件?

发布于 2024-08-30 17:42:50 字数 458 浏览 1 评论 0原文

我如何从 python 编写一个 .py 文件,使其类型不应该像“带有 Windows CRLF 的 ASCII 文件”,

因为当我在 Windows 内运行 file.write(data) 时,它会写入该文件,但是当我尝试 eval(open(file.py).read()) 它失败并给出语法错误,因为每行上都有 Windows CRLF......

请参阅错误日志 - 回溯

ERROR:web-services:[25]:     info = eval(tools.file_open(terp_file).read(-1))
ERROR:web-services:[26]:   File "<string>", line 1
ERROR:web-services:[27]:     {
ERROR:web-services:[28]:

how can I write a .py file from python such that its type should not be like 'ASCII file with Windows CRLF'

because when i run file.write(data) inside windows it write the file but when I try to
eval(open(file.py).read()) it fails and gives syntax error because of windows CRLF on each line......

see the error log - traceback

ERROR:web-services:[25]:     info = eval(tools.file_open(terp_file).read(-1))
ERROR:web-services:[26]:   File "<string>", line 1
ERROR:web-services:[27]:     {
ERROR:web-services:[28]:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

疯了 2024-09-06 17:42:50

您可以:

  1. 通过使用 open(file, 'wb') 打开文件以二进制模式写入文件,或者...
  2. 在使用 data 等写入之前,从字符串中去除 CR-LF .replace('\r','')

我会避开 exec 并使用 execfile 正如 SilentGhost 提到的

You can:

  1. Write the file in binary mode by opening it with open(file, 'wb') or...
  2. Strip the CR-LFs from the string before writing it with something like data.replace('\r','')

I would steer clear of exec and use execfile as mentioned by SilentGhost.

原野 2024-09-06 17:42:50

问题不在于 CRLF,而在于 eval 用于评估单个表达式,而不是整个程序。

您可以使用 exec 从字符串执行程序,或使用 execfile 直接从文件执行程序。

无论如何,要回答您最初的问题,您可以通过以二进制模式打开文件来避免编写 CRLF:f = open(filename, 'wb')

The problem is not with the CRLF, but that eval is for evaluating a single expression, not an entire program.

You can use exec to execute a program from a string, or execfile to execute it directly from a file.

To answer your original question anyway, you can avoid writing CRLF by opening the file in binary mode: f = open(filename, 'wb')

眼眸印温柔 2024-09-06 17:42:50

我认为您正在寻找 execfile 函数。

I think you're looking for execfile function.

十年不长 2024-09-06 17:42:50

只需以二进制模式打开文件:open("myfile.py", "rwb")

Just open the file in binary mode: open("myfile.py", "rwb")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文