【发布时间】:2016-10-31 13:18:34
【问题描述】:
我遇到了一个我不太了解如何克服的问题。我正在尝试在 python 中创建一个子进程来运行另一个 python 脚本。不太难。问题是当 python 文件包含超长字符串时,我无法解决 EOF 错误。
这是我的文件的示例。
子进程.py:
### call longstr.py from the primary pyfile
subprocess.call(['python longstr.py'], shell = True)
Longstr.py
### called from subprocess.py
### the actual string is a lot longer; this is an example to illustrate how the string is formatted
lngstr = """here is a really long
string (which has many n3w line$ and "characters")
that are causing the python file to state the file is ending early
"""
print lngstr
终端打印机错误
SyntaxError: EOF while scanning triple-quoted string literal
作为一种解决方法,我尝试删除所有换行符以及所有空格,以查看是否是由于它是多行的。仍然返回相同的结果。
我的假设是,当子进程正在运行并且 shell 正在对文件内容做一些事情时,当到达新行时,shell 本身就会吓坏,这就是终止进程的原因;不是文件。
让子进程运行这样的文件的正确解决方法是什么?
感谢您的帮助。
【问题讨论】:
-
为什么要让其他 Python 脚本在单独的进程中运行?
import会更高效,并为您提供更多控制权,除非您专门尝试重新实现多处理,效果不佳。 -
该文件是动态创建的,因此在我
open和write文件之前无法将导入添加到我的主文件的头部。这只是我想知道该怎么做的事情。 -
摆脱无用的
shell=True将使“穷人”不那么惊天动地。然后,您需要将命令转换为字符串列表。subprocess.call(['python', 'longstr.py']) -
感谢您的反馈@tripleee
标签: python python-2.7 shell subprocess