Python Forum
How to use subprocess send commands to windows shell - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to use subprocess send commands to windows shell (/thread-22648.html)



How to use subprocess send commands to windows shell - hlhp - Nov-21-2019

I want to send multiple commands to a shell program depends on the output.
But I can not figure out how to send multiple commands.

Python ver 3.6.8
Windows 10

Base on the reference, but my code is not workring, it only print the "ipconig", the "dir" is not working and raising error.
from subprocess import Popen, PIPE

process = Popen("ipconfig", stdin=PIPE, stdout=PIPE, shell = True, cwd = "d:")
print(repr(process.stdout.read()))
process.stdin.flush()
process.stdin.write(b'dir\n')
print(repr(process.stdout.read()))
process.stdin.flush()
process.stdin.write(b'tasklist\n')
print(repr(process.stdout.read()))
Error:
Quote:Traceback (most recent call last):
File "d:\Inbox\Desktop\delete m2e.py", line 8, in <module>
process.stdin.flush()
OSError: Errno 22 Invalid argument



RE: How to use subprocess send commands to windows shell - Larz60+ - Nov-21-2019

Here's a modified version from python docs: https://docs.python.org/3/library/subprocess.html
run on Linux
import shlex, subprocess


def run_subprocess(command_line):
    args = shlex.split(command_line)
    print(args)
    p = subprocess.Popen(args) # Success!


if __name__ == '__main__':
    run_subprocess('/bin/ls -latr')
    run_subprocess('ls -latr /home')



RE: How to use subprocess send commands to windows shell - hlhp - Nov-25-2019

(Nov-21-2019, 07:27 PM)Larz60+ Wrote: Here's a modified version from python docs: https://docs.python.org/3/library/subprocess.html
run on Linux

Thank you for your reply Larz60+.

From my understanding, your code is calling 2 subprocess.

What I want to do is to call one subprocess, then read that process's outputs, then send other commands to that process.


RE: How to use subprocess send commands to windows shell - LeanbridgeTech - Nov-26-2019

How to use subprocess send commands to windows shell
See : https://www.pythonforbeginners.com/os/subprocess-for-system-administrators
Run the command described by "args".
We can run the command line with the arguments passed as a list of strings
(example 1) or by setting the shell argument to a True value (example 2)
Note, the default value of the shell argument is False.
Let's look at two examples where we show the summary of disk usage using
subprocess.call()