【问题标题】:Python Popen subprocess lookup dictionary cannot write or read (or anything)Python Popen 子进程查找字典无法写入或读取(或任何东西)
【发布时间】:2018-11-06 19:17:08
【问题描述】:

所以我将这个不和谐的机器人放在一起,它可以向服务器执行命令来托管一些游戏。

我有一个格式为 { 'Game Name' : subprocess.Popen() }

的字典
subprocess_LOOKUP = {}

我们需要存储以供以后即时注入命令以更改游戏模式等。

我已将代码简化为两个小函数以清楚地显示问题。

import subprocess
from subprocess import PIPE, STDOUT

subprocess_LOOKUP = {}

def gamestart(game, startcmd):

    #Open pipe with all parameters to read, write and communicate
    p = subprocess.Popen(startcmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=PIPE, shell=True)

    subprocess_LOOKUP.update({ game : p }) #Store into dictionary here


def gameinput(game, cmd):

    p = subprocess_LOOKUP[game]     #Retrieve from dictionary

    print(cmd)                      #Prints the command I want to input into the shell
    print(p.stdout.readline())      #Does Nothing (prints no errors)

    p.stdin.write(str.encode(cmd))  #Does Nothing (prints no errors)
    p.communicate()[0]              #Does Nothing (prints no errors)
    p.stdin.close()                 #Does Nothing (prints no errors)

稍后当我访问字典时,对 subprocess.Popen() 的引用似乎不存在?尝试写入、读取或与进程通信什么都不做,因为也不会打印任何错误!

通过查看此处的其他类似问题,我尝试了多种方法分别从标准输入或标准输出写入或读取,但仍然没有任何反应。我是否完全错过了某些事情,或者我需要做些什么?

【问题讨论】:

  • 刚刚尝试使用 p = subprocess_LOOKUP.get(game) 仍然无效。

标签: python dictionary subprocess popen


【解决方案1】:

您的印象是全局变量是在进程之间共享的。 It is not。您的选择是:

  1. 使用multiprocessing.Array 或multiprocessing.Value 共享状态。
  2. 使用multiprocessing.Manager。
  3. 使用某种 IPC。

Manager 似乎更适合您的问题,因为它允许您使用字典。

【讨论】:

  • 完全忽略了,该死的,非常感谢!并建议您认为哪一个,谢谢:)
  • 我会使用 multiprocessing.Manager,除非性能是一个问题(它会创建另一个进程,所以,你知道,资源和东西)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 2017-07-24
  • 2011-09-13
  • 1970-01-01
相关资源
最近更新 更多