【问题标题】:How do I make a python program give a command to a command shell? [closed]如何让 python 程序向命令 shell 发出命令? [关闭]
【发布时间】:2014-01-20 09:40:59
【问题描述】:

如何让 python 程序文本作为输入传递给另一个进程?特别是命令外壳,而不是命令行!

不作为运行方式

example.exe --doSomething -i random.txt -o random1.txt

但是作为

example.exe
# example shell loading
# and then in loaded shell
> doSomething -i random.txt -o random1.txt

编辑后的帖子:

如何让 python 程序在命令行中将输入传递到另一个窗口?我想这样做:

something = raw_input('Waddaya wanna do?')
if something == 'Halt!':
        placeholder('exit')
if something == 'Get help!':
        placeholder('help %COMMAND%')

placeholder() 代表将括号中的内容传递给命令外壳的命令。 I.E. 如果 processname = java.exe,它会将 'exit' 传递给 'java.exe'。

【问题讨论】:

标签: python windows shell ipc


【解决方案1】:

基本要点是您要使用subprocess 并将stdin 参数以及stdout 和stderr 参数作为PIPE 传递。

 p = subprocess.Popen(args, *,
                      stdout=subprocess.PIPE,
                      stdin=subprocess.PIPE)

这允许您使用 p 向子进程发送和接收消息:

p.stdin.write('Some input\n')
...
x = p.stdout.readline()
...

这里有一些很好的例子:

read subprocess stdout line by line

Python - How do I pass a string into subprocess.Popen (using the stdin argument)?

【讨论】:

    【解决方案2】:

    您似乎正在寻找subprocess.popen,请参阅tutorial 中的示例:

    可以以非常相似的方式写入进程。如果我们想向进程的标准输入发送数据,我们需要使用stdin=subprocess.PIPE 创建Popen 对象。 为了测试它,让我们编写另一个程序(write_to_stdin.py),它简单地打印 Received: 然后重复我们发送的消息:

    # write_to_stdin.py
    import sys
    input = sys.stdin.read()
    sys.stdout.write('Received: %s'%input)
    

    要向标准输入发送消息,我们将要发送的字符串作为输入参数传递给communicate():

    >>> proc = subprocess.Popen(['python', 'write_to_stdin.py'],  stdin=subprocess.PIPE)
    >>> proc.communicate('Hello?')
    Received: Hello?(None, None)
    

    【讨论】: