Akshat Goel
Akshat Goel

Reputation: 528

Calling multi-level commands/programs from python

I have a shell command 'fst-mor'. It takes an argument in form of file e.g. NOUN.A which is a lex file or something. Final command : fst-mor NOUN.A

It then produces following output:

analyze>INPUT_A_STRING_HERE
OUTPUT_HERE

Now I want to put call that fst-mor from my python script and then input string and want back output in the script.

So far I have:

import os
print os.system("fst-mor NOUN.A")

Upvotes: 0

Views: 164

Answers (4)

nat
nat

Reputation: 184

A sample that communicates with another process:

pipe = subprocess.Popen(['clisp'],stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(response,err) = pipe.communicate("(+ 1 1)\n(* 2 2)")
#only print the last 6 lines to chop off the REPL intro text. 
#Obviously you can do whatever manipulations you feel are necessary 
#to correctly grab the input here
print '\n'.join(response.split('\n')[-6:])

Note that communicate will close the streams after it runs, so you have to know all your commands ahead of time for this method to work. It seems like the pipe.stdout doesn't flush until stdin is closed? I'd be curious if there is a way around that I'm missing.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121296

You want to capture the output of another command. Use the subprocess module for this.

import subprocess

output = subprocess.check_output('fst-mor', 'NOUN.A')

If your command requires interactive input, you have two options:

  • Use a subprocess.Popen() object, and set the stdin parameter to subprocess.PIPE and write the input to the stdin pipe available. For one input parameter, that's often enough. Study the documentation for the subprocess module for details, but the basic interaction is:

    proc = subprocess.Popen(['fst-mor', 'NOUN.A'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    output, err = proc.communicate('INPUT_A_STRING_HERE')
    
  • Use the pexpect library to drive a process. This let's you create more complex interactions with a subprocess by looking for patterns is the output it generates:

    import pexpect
    
    py = pexpect.spawn('fst-mor NOUN.A')
    py.expect('analyze>')
    py.send('INPUT_A_STRING_HERE')
    output = py.read()
    py.close()
    

Upvotes: 3

jfs
jfs

Reputation: 414079

You could try:

from subprocess import Popen, PIPE

p = Popen(["fst-mor", "NOUN.A"], stdin=PIPE, stdout=PIPE)
output = p.communicate("INPUT_A_STRING_HERE")[0]

Upvotes: 1

user2079098
user2079098

Reputation: 132

You should use the subprocess module subprocess module

In your example you might run:

subprocess.check_output(["fst-mor", "NOUN.A"])

Upvotes: -1

Related Questions