#3 Able to run commands in background
Closed Opened by mrniranjan.

In our automation at times it 's required to run certain commands in background for example running tcpdump in background while we are doing certain commands to verify certain events.

The current run_command method is not possible to run commands in background. The workaround is create a local file which contains commands and specify & . Copy the file to the remote system and then call the script, this is inefficient.

I have a small rough patch which calls get_pty() and immediately call exec_command method Paramikochannel. Though this achieves the objective, I would like to get some more views if there is better method of doing this.


The plugin was designed so that it would be possible to run commands asynchronously, but this behavior was not needed, so it wasn't exposed in the API, tested or documented. The only thing that makes programs run "in the foreground" is that run_command explicitly waits for the process to exit.

The soulution would be to add a background argument to run_command, which would skip the command.wait() call near the end of the function. The caller then needs to call command.wait itself before accessing the command's results.

I did try this method though the command executed in background, but py.test would not finish and hang there till the command finished . Probably i was doing something wrong.

Ah, right. You need to call command.wait() on the result. For processes like tcpdump that don't end, you need to signal them using kill or similar – maybe that should be added to the API as well.

is there a way to kill the terminal while closing the connections as part of teardown ?

That would need to be added.

How would we signal a kill?

cmd1 = host.run_command(cmd1_args_list, background=True)
cmd2 = host.run_command(cmd2_args_list)
host.kill_command(cmd1)

Then maybe have kill_command run kill and then command.wait?

Instead of host.kill_command(cmd1), I'd say cmd1.kill() followed by cmd1.wait().

The reason for separate wait() would be similarity to Python's subprocess module, where kill() doesn't wait for the process to end.

PR: https://pagure.io/python-pytest-multihost/pull-request/5 addresses this issue.

Metadata Update from @mrniranjan:
- Issue assigned to mrniranjan

Metadata Update from @mrniranjan:
- Issue status updated to: Closed (was: Open)

Metadata