2
我想创建一个python脚本,它将允许一些与Cadence技能(命令行界面)接口。我想要将任何输出导向到shell。我觉得这应该很简单,但我无法让它工作。但是,使用Popen
时,我在命令行上看不到任何输出,并且我不确定communicate()
是否正确发送该命令。这是我到目前为止:使用Python通过命令行与程序通信
import re, array
import sys
from subprocess import call
from subprocess import Popen, PIPE, STDOUT
from threading import Thread
import os
#SET THESE VARIABLES
LibraryPath = 'path_to_library'
skillPath = 'path_to_cadence'
#Cadence Environment path
cadence_env= 'source /mscad/apps/bin/mscad_bash/cadtools --env cadence'
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
# Change to proper Cadence Directory
# Debugging Variables
etype = 0; value = 0; traceback = 0
NewPath = cd(LibraryPath)
NewPath.__enter__()
# Open Cadence Virtuoso in Shell Mode
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # python 3.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
p = Popen(['/bin/bash', '-i', '-c', 'cadence_env cmos12s0; virtuoso -nograph'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
# read line without blocking
try: line = q.get_nowait() # or q.get(timeout=.1)
except Empty:
print('no output yet')
else: # got line
print(line)
load_command = "load(\""+skillPath+"\")"
print load_command
p.communicate(input=load_command)
print "Command Sent ..."
NewPath.__exit__(etype, value, traceback)
call(["ls -l"], shell=True)
在此先感谢您的帮助。
什么是特定问题? (用step_step来描述单词_)你预期会发生什么,取而代之的是什么?不要发布你拥有的所有代码,[改为创建一个最小但完整的代码示例](http://stackoverflow.com/help/mcve) - 使用一个虚拟孩子Python脚本代替'cadence_env'来复制问题。我不明白你为什么要使用*“在python的subprocess.PIPE上非阻塞读取”的代码*问题?您应该首先学习如何使用'.communicate()',例如使用'input'参数,设置'stdin = PIPE'并在控制台中查看输出,移除'stdout = PIPE'。 – jfs
谢谢,我会尝试使用通信的一个更简单的例子,然后相应地编辑我的文章。 – digitaLink