What's the closest I can get to calling a Python function using a different Python version?
<p>Say I have two files:</p>

<pre><code># spam.py
import library_Python3_only as l3

def spam(x,y)
    return l3.bar(x).baz(y)
</code></pre>

<p>and</p>

<pre><code># beans.py
import library_Python2_only as l2

...
</code></pre>

<p>Now suppose I wish to call <code>spam</code> from within <code>beans</code>. It's not directly possible since both files depend on incompatible Python versions. Of course I can <code>Popen</code> a different python process, but how could I pass in the arguments and retrieve the results without too much stream-parsing pain?</p>

<p>Assuming the caller is Python3.5+, you have access to a nicer <a href="https://docs.python.org/3/library/subprocess.html">subprocess</a> module. Perhaps you could user <code>subprocess.run</code>, and communicate via pickled Python objects sent through stdin and stdout, respectively. There would be some setup to do, but no parsing on your side, or mucking with strings etc.</p>

<p>Here's an example of Python2 code via subprocess.Popen</p>

<pre><code>p = subprocess.Popen(python3_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(pickle.dumps(python3_args))
result = pickle.load(stdout)
</code></pre>

python compatibility popen