如何在python中通过stdin发送多个字符串



我将父代码的字符串Router_Status[Router]='ON'发送到新进程

proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
+ Router + '.py', Router,
json.dumps(graph),
json.dumps(As_numbers_dict)],
shell=False, stderr=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
proc[Router].stdin.write(bytes(Router_Status[Router],
encoding='utf-8') + b'n')

子进程是

Router_Status[Router]=sys.stdin.readline().strip()
path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
f.write(Router_Status[Router])

但它不起作用! 然后我将第二个字符串 Router_Status[Router]='OFF' 传递给进程 proc[Router].stdin.write(bytes(Router_Status[Router], encoding='utf-8')

proc[Router].stdin.flush()

它仍然无能为力!

好的,所以我不完全熟悉你传递给子进程的参数。Popen() 所以我无法检查这些是否正确。但是,我确实对子流程模块略知一二,并且需要考虑查看您的代码:

  • 使用shell=False不需要显式定义,因为它是标准设置(尽管,如果您出于某种原因想明确它,那当然没关系)。
  • stderr=False的参数不正确。它必须是None或类似subprocess.PIPE的东西。

然后,由于您使用的是 Python3.x,文档声明:

警告- 使用 communication() 而不是 .stdin.write、.stdout.read 或 .stderr.read 以避免由于任何其他操作系统管道而导致的死锁 缓冲区填满并阻止子进程。

所以你最好使用proc[Router].communicate(input="your standard input, meaning your stdin")

它还指出:

Popen.stdin- 如果 stdin 参数是 PIPE,则此属性为 由 open() 返回的可写流对象。如果编码或 指定了错误参数或universal_newlines参数为 没错,流是文本流,否则它是字节流。如果 stdin 参数不是 PIPE,此属性是 None。

在您的情况下,意味着 stdin 确实应该通过字节流。

总的来说,我猜你应该做这样的事情:

proc[Router] = subprocess.Popen([sys.executable, os.getcwd() + '/'
+ Router + '.py', Router,
json.dumps(graph),
json.dumps(As_numbers_dict)],
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
proc[Router].stdin.communicate(str(Router_Status[Router]).encode())

但是,我仍然想知道,您为什么包括:

path = os.path.expanduser('~' + '/BGP_Routers/' + Router)
with open(path + '/Router_Status.txt', 'w') as f:
f.write(Router_Status[Router])

因为它基本上与子过程无关。Popen() 语句。它所做的只是将用户输入写入文本文件,该文件只会捕获最新的输入。如果要保存所有用户输入,请将'w'更改为'a'(这会将文件置于追加模式而不是写入模式)。

最新更新