【问题标题】:Communicating with Program by command line using Python使用 Python 通过命令行与程序通信
【发布时间】:2015-10-09 22:40:40
【问题描述】:

我正在尝试创建一个 python 脚本,该脚本将允许使用 Cadence Skill 的某些接口(命令行接口)。我希望将任何输出定向到外壳。我觉得这应该很简单,但我还不能让它工作。但是,使用Popen,我在命令行上看不到任何输出,而且我不确定communicate() 是否正确发送了命令。这是我目前所拥有的:

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)

提前感谢您的帮助。

参考文献

【问题讨论】:

  • 具体问题是什么? (用词逐步描述)你期望会发生什么,反而会发生什么?不要发布您拥有的所有代码,create a minimal but complete code example instead - 使用虚拟子 Python 脚本而不是 cadence_env 来复制问题。我不明白您为什么要使用 "Non-blocking read on a subprocess.PIPE in python" 问题中的代码?您应该首先学习如何使用.communicate(),例如,使用input 参数,设置stdin=PIPE 并在控制台中查看输出,删除stdout=PIPE
  • 谢谢,我将尝试一个更简单的使用通信的示例,然后相应地编辑我的帖子。

标签: python popen cadence cadence-virtuoso


【解决方案1】:

我让它变得比我的应用程序需要的更复杂;但是我遇到的主要问题是我在向程序发送命令时丢失了\n。此外,删除stdout=PIPE 允许程序的所有输出直接进入控制台。

proc = Popen(['/bin/bash', '-i', '-c', 'Command_To_Open_Program'], stdin=PIPE, stderr=STDOUT)
command = "command_to_program\n"
proc.stdin.write(command)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2023-03-26
    • 2012-05-22
    相关资源
    最近更新 更多