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

时间:2017-03-28 15:04:10

标签: python python-3.x subprocess

我发送字符串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()

它仍然没有做任何事情!

1 个答案:

答案 0 :(得分:0)

好的,所以我不完全熟悉你传递给subprocess.Popen()的参数,所以我无法检查它们是否正确。但是我对子进程模块知道了一两件事,并且有一些事情要考虑查看你的代码:

  • 使用shell=False不需要明确定义,因为它是标准设置(但是,如果你想明白某个原因,那当然没关系)。
  • 参数stderr=False不正确。它必须是None或类似subprocess.PIPE

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

  

警告 - 使用communic()而不是.stdin.write,.stdout.read或   .stderr.read以避免由于任何其他OS管道导致的死锁   缓冲填充和阻止子进程。

所以你最好使用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])

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

相关问题