[python-win32] Inheriting a command line - or how to efficiently replace Unix' os.execvpe

Sebastian M. Ernst ernst at pleiszenburg.de
Wed May 12 07:00:24 EDT 2021


Hi all,

I am dealing with a Python script line - which does, after some
preparation work, launch `ssh` (Windows 10 does have native `OpenSSH`
now). My script is actually a small CLI tool. On Unix-like systems, at
the end of its life, the Python script replaces itself with the `ssh`
client, so the user can now interact with `ssh` directly (i.e. run
arbitrary commands on the remote machine etc):

`os.execvpe('ssh', ['ssh', '-o', 'foo', 'user at host'], os.environ)`

`os.execvpe` is present in the Python standard library on Windows, but
it does not replace the original (Python) process. Windows is apparently
lacking relevant POSIX semantics. It starts the new process more or less
like a child, but does not allow it to control the command line.
Instead, both the Python process and the child die. The child merely
manages to produce a few lines of output before that.

After having poked around in MSDN, I think I can make the child
"inherit" the command line, i.e. allow it to control it. However, I am
having trouble figuring out how. My most successful bad solution looks
as follows (directly using one of `win32`'s examples for simplicity):

```python
from win32.Demos.winprocess import Process
from shlex import join
Process(join(['ssh', '-o', 'foo', 'user at host']))
```

`ssh` opens into a second, new `cmd.exe` window and can be interacted
with. The original `cmd.exe` window with Python in it remains open,
Python itself quits, returning control to `cmd.exe` itself.

I guess it comes down to configuring `win32process.STARTUPINFO`
correctly, but even after heaving read tons of documentation on it, I am
somehow failing to make sense of it ...

---

Full disclosure: I published this question on SO a while ago and even
put a bounty on it. No meaningful reply so far. In case someone wants to
earn the points before they're gone ...

https://stackoverflow.com/q/67371606/1672565

Best regards,
Sebastian


More information about the python-win32 mailing list