繁体   English   中英

使用 Python 子进程处理交互式 shell

[英]Handling interactive shells with Python subprocess

我正在尝试使用多处理池来运行基于控制台的游戏的多个实例(地牢爬行石汤——自然用于研究目的)来评估每次运行。

过去,当我使用池来评估类似的代码(遗传算法)时,我使用subprocess.call来拆分每个进程。 但是,由于 dcss 具有很强的交互性,因此共享子外壳似乎有问题。

我有我通常用于这种事情的代码,爬行取代了我抛出 GA 的其他应用程序。 有没有比这更好的方法来处理高度交互的 shell? 我曾考虑为每个实例启动一个屏幕,但认为有一种更清洁的方法。 我的理解是shell=True应该产生一个子外壳,但我想我以每次调用之间共享的方式产生一个。

我应该提到我有一个运行游戏的机器人,所以我不希望用户端发生任何实际交互。

# Kick off the GA execution
pool_args = zip(trial_ids,run_types,self.__population)
pool.map(self._GAExecute, pool_args)

---

# called by pool.map 
def _GAExecute(self,pool_args):
  trial_id       = pool_args[0]
  run_type       = pool_args[1]
  genome         = pool_args[2]
  self._RunSimulation(trial_id)

# Call the actual binary
def _RunSimulation(self, trial_id):
  command = "./%s" % self.__crawl_binary
  name    = "-name %s" % trial_id
  rc      = "-rc %s" % os.path.join(self.__output_dir,'qw-%s'%trial_id,"qw -%s.rc"%trial_id)
  seed    = "-seed %d" % self.__seed
  cdir    = "-dir %s" % os.path.join(self.__output_dir,'qw-%s'%trial_id)

  shell_command = "%s %s %s %s %s" % (command,name,rc,seed,cdir)
  call(shell_command, shell=True)

您确实可以将 stdin 和 stdout 与文件相关联,如@napuzba 的回答所示:

fout = open('stdout.txt','w')
ferr = open('stderr.txt','w')
subprocess.call(cmd, stdout=fout, stderr=ferr)

另一种选择是使用Popen而不是call 不同之处在于调用等待完成(阻塞)而 Popen 不是,请参阅子进程 Popen 和调用之间的区别什么(如何使用它们)?

使用 Popen,您可以将 stdout 和 stderr 保留在您的对象中,然后在以后使用它们,而不必依赖于文件:

p = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
stderr = p.stderr.read()
stdout = p.stdout.read()

这种方法的另一个潜在优势是你可以运行多个 Popen 实例而无需等待完成而不是拥有线程池:

processes=[
  subprocess.Popen(cmd1,stdout=subprocess.PIPE, stderr=subprocess.PIPE),
  subprocess.Popen(cmd2,stdout=subprocess.PIPE, stderr=subprocess.PIPE),
  subprocess.Popen(cmd3,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
]

for p in processes:
  if p.poll():
     # process completed
  else:
     # no completion yet

附带说明一下,如果可以,您应该避免shell=True ,如果您不使用它,Popen 需要一个列表作为命令而不是字符串。 不要手动生成此列表,而是使用shlex它将为您处理所有极端情况,例如:

Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

为每次调用指定具有唯一文件句柄的标准输入、标准输出和标准错误:

import subprocess
cmd  = ""
fout = open('stdout.txt','w')
fin  = open('stdin.txt','r')
ferr = open('stderr.txt','w')
subprocess.call(cmd, stdout=fout , stdin = fin , stderr=ferr )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM