# Problem with Calling Prolog from Python

**URL:** <https://swi-prolog.discourse.group/t/problem-with-calling-prolog-from-python/7350>\
**Category:** PlDoc\
**Created:** [April 2, 2024, 6:54pm UTC](https://swi-prolog.discourse.group/t/problem-with-calling-prolog-from-python/7350 "2024-04-02T18:54:21Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![peter.ludemann](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/peter.ludemann/32/48_2.png) [@peter.ludemann](https://swi-prolog.discourse.group/u/peter.ludemann)\
**Post date:** [April 4, 2024, 3:38pm UTC](https://swi-prolog.discourse.group/t/problem-with-calling-prolog-from-python/7350/5 "2024-04-04T15:38:49Z")

</div>

> [@jan](#):
>
> If anything goes wrong the query is not closed and Prolog gets upset

Python has something similar to Prolog’s setup\_call\_cleanup/3, namely “context managers”. One common usage is to open a file and have it automatically closed when not needed, e.g.:

```python
with open("some file", "r") as infile, open("copy of some file", "w") as outfile:
   for line in file:
      outfile.write(line)

```

but something similar could be done for queries, so that everything gets cleaned up properly.

For more details, see the [with](https://docs.python.org/3/reference/compound_stmts.html#with) statement, [context managers](https://docs.python.org/3/reference/datamodel.html#context-managers), and [contextlib](https://docs.python.org/3/library/contextlib.html).

---

_[View the full topic](https://swi-prolog.discourse.group/t/problem-with-calling-prolog-from-python/7350)._
