简体   繁体   中英

How is it possible to send commands to other program from python?

Here is the problem: I need to start a program and send there commands from python. For example it may be cmd and I send there path to cd and dir the contains(work on windows). I tried lots of ways but cannot still find the solution.

I can't understand why it isn't working even on simpliest examples. I came to conclusion that subprocess.Popen may be the best way for my goal. Here is what I tried.

In first block of task the program only prints the contains of the directory of python file instead of given and in second block it prints nothing for some reason

Please may be anyone knows how to do it the right way?

from subprocess import Popen, PIPE


if __name__ == "__main__":

    path_for_dir = "C:\\Users\\Documents"

    class Console:
        def __init__(self):
            command = r"dir"
            self.console = Popen(
                command, stdin=PIPE, stdout=PIPE, shell=True, text=True
            )

        def read_output(self):
            result = []
            for line in self.console.stdout:
                result.append(line)
            for line in result:
                print(line)

        def cmd(self, cmd_string):
            self.console.stdin.write(cmd_string)
            self.console.stdin.close()

    c = Console()
    c.cmd(f"{path_for_dir}")
    print(c.read_output())

    print(f"NEXT")

    p = Popen(
        ["grep", "n"],
        stdout=PIPE,
        stdin=PIPE,
        stderr=PIPE,
        shell=True,
        universal_newlines=True,
    )
    p.stdin.write("one")
    p.stdin.write("two")
    p.stdin.write("three")
    testresult = p.communicate()[0]
    print(f"{testresult=}")
  1. You're not writing newlines in the one-two-three example at all. All grep sees is onetwothree . (That said, onetwothree would still match n , but I assume you do mean different lines since you have three different write calls.)
  2. You shouldn't use shell=True unless you need to. You can use shutil.which() to find a command like the shell would.
from subprocess import Popen, PIPE
from shutil import which

p = Popen(
    [which("grep"), "n"],
    stdout=PIPE,
    stdin=PIPE,
    stderr=PIPE,
    universal_newlines=True,
)
p.stdin.write("one\n")
p.stdin.write("two\n")
p.stdin.write("three\n")
testresult = p.communicate()[0]
print(f"{testresult=}")

prints out

testresult='one\n'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM