Skip to content Skip to sidebar Skip to footer

How Can I Communicate Between Two Python Scripts?

I have a 3d party python script which takes input from the command line. The relevant code from this script (input.py) looks like the following: import sys def chooseinput():

Solution 1:

Try:

p.stdin.write('a\n')
p.stdin.write('b\n')

Solution 2:

linuts answer works well in your simple example, but for the benefit of future readers, I would strongly recommend against using this methodology for communicating between Python scripts.

This method is a throwback to when few other options were available. Pexpect, bless its heart, may indeed be a good program, but it merely puts a happy face on a miserable interface technique. Command-line control such as this is often timing dependent, quickly making it tedious and error-prone. Use it only when you have no other choice.

Python brings many much more powerful methods to scripting. Unless you don't have access to script internals (with Python, you almost always do) you should instead write your harness.py script to import the 3-party script as a library and control it programmatically by calling its methods/functions directly.

Your current predicament may not allow it, but with Python scripts, command-line communication should be the last choice, not the first.

Solution 3:

You should check out Pexpect.

Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. The child application can be any executable (for instance, as in your case, another python script). It works similarly to the unix tool "expect".

Post a Comment for "How Can I Communicate Between Two Python Scripts?"