如何让python程序向命令shell发出命令?

时间:2014-01-02 20:40:04

标签: python windows shell ipc

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

不以

运行
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()代表命令,它将括号中的内容传递给命令shell。 I. E.如果processname = java.exe,它会将'exit'传递给'java.exe。'

2 个答案:

答案 0 :(得分:0)

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

  

写入流程可以以非常类似的方式完成。如果我们想要将数据发送到进程的stdin,我们需要使用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)
     

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

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

答案 1 :(得分:0)

基本要点是你想使用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)?