是否有类似于上下文管理器的东西,因此无需运行近输入端口?

发布于 2025-02-13 02:54:42 字数 495 浏览 0 评论 0原文

#!/usr/bin/env racket
#lang racket/base

(require net/url racket/port)
(require (planet neil/html-parsing:3:0))

(define p (get-pure-port (string->url "https://www.rosettacode.org/wiki/Web_scraping")))
(define my-html (port->string p))
(close-input-port p)

是否有另一种重写上述代码的方式,因此无需明确 指示(关闭输入 - 端口P)? 我牢记一些类似的呼叫输入文件涉及关闭的东西 端口读取完成的文件后(类似于)。

#!/usr/bin/env racket
#lang racket/base

(require net/url racket/port)
(require (planet neil/html-parsing:3:0))

(define p (get-pure-port (string->url "https://www.rosettacode.org/wiki/Web_scraping")))
(define my-html (port->string p))
(close-input-port p)

Is there another way of rewriting the above code so that there is no need to explicitly
instruct (close-input-port p)?
I have in mind something similar call-with-input-file that deals with closing
the port once the job of reading the file done (akin to context managers in Python).

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

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

发布评论

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

评论(1

风情万种。 2025-02-20 02:54:42

在这种特殊情况下,您可以使用 call/input-url

(define my-html
   (call/input-url (string->url "https://www.rosettacode.org/wiki/Web_scraping")
                   get-pure-port port->string))

它使用给定的连接功能从URL打开端口,使用该端口调用处理程序功能,然后在返回处理程序返回之前关闭端口值。

开放端口的许多方案和球拍特定的功能类别都具有等效物,例如call-input-input-file就像我在回答您的另一个问题的回答时所使用的那样。

In this particular case, you can use call/input-url:

(define my-html
   (call/input-url (string->url "https://www.rosettacode.org/wiki/Web_scraping")
                   get-pure-port port->string))

which opens a port from a URL using the given connection function, calls a handler function with that port, and closes the port before returning the handler's return values.

Many Scheme and Racket-specific function categories that open ports have equivalents, like the call-with-input-file like I used in an answer to another of your questions.

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