使用 urlencode、urlopen 上传文件 - 文本被截断,除非在之后调用 post.read()?

Uploading files with urlencode, urlopen - text truncated unless post.read() is called after?

我遇到了一些非常奇怪的行为,我希望有人能向我解释发生了什么。我浏览了官方 Python 文档,但没有看到任何可以解释我所看到内容的内容 - 如果我遗漏了什么,请为我指出。

我有一个(大)python 脚本,它包含价值约 150k 的文本,存放在 "content" 变量中,并将其上传到远程系统上的 Perl 脚本以进行日志记录。它使用 urllib 来执行此操作:

thash = {'file_name': file_name, 'contents':content}
upload = urlib.urlencode(thash)
post = urlib.urlopen("http://path.to.perl.script/log_writer.pl", upload)
#post.read()

问题是 "log_writer.pl" 写入的文件在看似随机选择的位置被截断,具体取决于 "content" - 的长度,除非我调用 post.read () 在我的 Python 脚本 .

中调用 urlopen 之后

我是 Python 的新手,对 Perl 还是很陌生,但我的理解是它不应该以这种方式工作。当我在 Python 脚本中本地调用 post.read() 时,为什么远程 Perl 脚本会写入整个文件?

您需要在请求之后对 'post' 中的响应对象执行一些操作。如果在程序中的那个点之后没有对 'post' 的任何引用(例如 post.read()、post.close() 等),python 将优化它离开并在 POST 完成之前让响应对象符合垃圾收集条件。

有关详细信息,请参阅:should I call close() after urllib.urlopen()?