简体   繁体   中英

How to run some other program interactively from a python script

I am new to python. I would like to run a "EDA tool" from python interactively. Here are the steps I wanted to follow:

  1. Start the tool
  2. Run the first command in the tool
  3. Check for the first command output or parse (in the main pyton) script
  4. Run the second command
  5. Parse the output in python script

[...]

x. Exit the tool

x+1. Do some post processing in main pyhon script

I am looking for some information or pointers related to it so that I can read on my own.

This depends on what you mean by a "command". Is each command a separate process (in the operating-systems definition of that word)? If so, it sounds like you need the subprocess module.

import subprocess
execNamePlusArgs = [ 'ls', '-l' ] # unix-like (i.e. non-Windows) example
sp = subprocess.Popen( execNamePlusArgs, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
stdout, stderr = sp.communicate() # this blocks until the process terminates
print( stdout )

If you don't want it to block until termination (eg if you want to feed the subprocess line-by-line input and examine its output line by line) then you would define stdin=subprocess.PIPE as well and then, instead of communicate , you might use calls to sp.stdin.writeline(whatever) , sp.stdout.readline() and sp.stderr.readline()

You should look into using something like python-fabric It allows you to use higher level language constructs such as context managers and makes the shell more usable with python in general.

Example usage:

from fabric.operations import local
from fabric.context_managers import lcd

with lcd(".."): # Prefix all commands with 'cd.. &&'
    ls = local('ls',capture=True) # Run 'ls' command and put result into variable
    print ls

>>> 
[localhost] local: ls
Eigene Bilder
Eigene Musik
Eigene Videos
SynKernelDiag2015-11-07_10-01-13.log
desktop.ini
foo
scripts

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