Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture print output from a c-module in python

I want to store this verbose output of pycosat to a string:

import pycosat
cnf = [[1, -5, 4], [-1, 5, 3, 4], [-3, -4]]
pycosat.solve(cnf,verbose=5)

I found various solutions, e.g. Capture stdout from a script in Python

However the solutions based on stringIO() don't capture the pycosat output. The output gets printed normally, and an empty string is captured.

I think this has to do with the fact that pycosat is a binding to the c-library picosat but I do not know how to deal with this.

This solution doesn't work either https://stackoverflow.com/a/29834357/4270148

Python will freeze at

out.stop()

ipython will also freeze at

sys.stdout = StringIO()

which may have something to do with it.

I did not try using the solutions using subprocess, because I need the local variable cnf, and it doesn't really make sense to pass it into a subprocess.

I don't know if it should be relevant, but I am using conda 3.14.1 on osx-64

like image 267
Tivaro Avatar asked Mar 24 '26 09:03

Tivaro


1 Answers

The subprocess solution found here https://stackoverflow.com/a/5136686/4270148, actually works!

import subprocess
proc = subprocess.Popen(["python", "-c",
    "cnf = [[1, -5, 4], [-1, 5, 3, 4], [-3, -4]];\
    import pycosat;\
    pycosat.solve(cnf,verbose=5);"],
    stdout=subprocess.PIPE)
out = proc.communicate()[0]

I don't like that the way the program is passed (as an eval-string), but at least it works.

like image 105
Tivaro Avatar answered Mar 26 '26 23:03

Tivaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!