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