3

I'm trying to test a small server application using python. The application is working a bit like a remote shell - it takes an input and outputs some data based on the input.

My initial try looks like this:

#!/usr/bin/python3
import subprocess

nc = subprocess.Popen(['/usr/bin/ncat','127.0.0.1','9999'], stdin = 
subprocess.PIPE, stdout = subprocess.PIPE)

nc.stdin.write(b'test')

This doesn't work and tells me:

write: Broken pipe

However when i test this out in a python3 interactive intepreter everything seems to be working just fine:

$ /usr/bin/python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> nc = subprocess.Popen(['ncat','127.0.0.1','9999'], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> nc.stdin.write(b'test')
4

When I run the ncat in the shell it also waits for the input as expected.

So what is going on? How is the interactive interpreter different from running a script and why does it affect the subprocesses?


Some notes:

  • I don't want to use sockets myself. The server I'm testing is run via xinetd, which means that the executable can also be tested by running it directly. With the current solution I could change ['/usr/bin/ncat','127.0.0.1','9999'] to ['./server_executable'] and test everything without the networking inbetween. With sockets I'd lose this functionality.
  • I know about pexpect and I even consider using it. Even if I end up not using the subprocesses I'd like to know what the heck is happening here.
  • When I provide the server executable to Popen everything works fine. This could hint that there is some problem with ncat and how it is run (don't know if it's relevant but I use ncat version 7.40).
ja2142
  • 892
  • 15
  • 23
  • did you try to use [`communicate()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate)? – Michael Kopp Jul 08 '19 at 22:31
  • I have more then one thing to do, and some actions are dependent on an output from previous steps. `comunicate()` doesn't work because it waits for the subprocess to terminate. – ja2142 Jul 08 '19 at 22:34
  • How are you executing the standalone script? – John Gordon Jul 08 '19 at 22:38
  • Is `/usr/bin/ncat` the same as `ncat`? – John Gordon Jul 08 '19 at 22:39
  • I tried `./script.py` and `/usr/bin/python3 script.py`. Neither is working as expected. – ja2142 Jul 08 '19 at 22:40
  • I changed `ncat` to `/usr/bin/ncat` to check if it's some problem with paths, but they are the same executable and only ncat on that system, as far as I know. – ja2142 Jul 08 '19 at 22:42

0 Answers0