【问题标题】:Running TerrariaServer through python通过 python 运行 TerrariaServer
【发布时间】:2020-02-01 07:26:52
【问题描述】:

我遇到的第一个问题是我不知道如何响应命令提示符。

bat_location = "F:/SteamLibrary/steamapps/common/Terraria"
os.chdir(bat_location)
os.system("TerrariaServer.exe -steam -lobby friends -config serverconfig.txt")

所有这些都有效,但是当我想响应询问我要运行哪个世界的命令提示符时(世界由 1 - n(世界数量)的数字索引)我不知道如何回应它。

我已经查看了所有的谷歌,但代码似乎不起作用。

所以基本上我需要的是当一个 cmd 询问我时:

Choose World:

我想自动回复数字 10。

os.system("10")

这似乎没有任何作用,我也尝试过很多子流程,但我显然迷路了。

感谢您的帮助!

编辑 NR.1:

Welp,现在我已经尝试过了:

bat_location = r'F:\SteamLibrary\steamapps\common\Terraria'
with Popen('TerrariaServer.exe -steam -lobby friends -config serverconfig.txt',
    cwd=f'{bat_location}', stdin=PIPE, shell=True) as proc:
      proc.stdin.write(b'10\n')

它所做的一切,我根据响应猜测,它只是循环播放。

编辑 NR.2:

我将关闭这个并开始一个新的线程,因为我的问题完全源于原始。

【问题讨论】:

  • 看看"Python subprocess and user interaction." 的答案你几乎肯定想使用subprocess,而不是os.system
  • 好的,所以我尝试使用它:proc = subprocess.Popen(['cd F:/SteamLibrary/steamapps/common/Terraria', 'TerrariaServer.exe -steam -lobby friends -config serverconfig.txt '], stdout=PIPE, stdin=PIPE, stderr=STDOUT) 但它只是抛出一个错误 [WinError 2] 系统找不到指定的文件我错过了什么吗??
  • 这是试图运行两个不同的命令; subprocess 函数每个只运行一个命令。要设置工作目录,请使用 cwd 关键字参数。
  • 什么时候在“TerrariaServer.exe etc”之前或之后指定它?
  • cwd 必须作为关键字参数在任何位置参数之后给出。但是,您可能希望使用完整路径来运行程序,大概是F:/SteamLibrary/steamapps/common/Terraria/Terraria.exe

标签: python


【解决方案1】:

从您最近的几次 cmets 中,我意识到您在使用 Popen 时遇到的问题。当你传递stdout=PIPEstderr=PIPE 时,进程的输出被管道捕获,所以除非你从管道读取,否则你不会看到它们。

下面是一个您应该能够使用的简单示例:

import subprocess
from subprocess import PIPE
from textwrap import dedent

with open('tmp.py', 'w') as f:
    f.write(dedent("""
            print(input())
            print(input())
            """))

with subprocess.Popen(['python3', 'tmp.py'], stdin=PIPE) as proc:
    proc.stdin.write(b'Hello, world!\n') # write to the process' input
    proc.stdin.write(b'Good bye, world!\n') # write to the process' input

如果要在 Python 中从函数中读取数据,可以使用stdout=PIPE,然后使用proc.stdout.read 等,但您可能需要注意如何从阻塞读取函数中获取数据。

【讨论】:

    【解决方案2】:

    好的,到目前为止我已经尝试过了,从你的回答中我有点明白了,但是这个:

    bat_location = r'F:\SteamLibrary\steamapps\common\Terraria'
        Popen('TerrariaServer.exe -steam -lobby friends -config serverconfig.txt',
                     cwd=f'{bat_location}', stdin=PIPE, stdout=PIPE, shell=True) as proc:
        proc.stdout.read()
    proc.stdin.write(b'10\n')
    proc.stdout.read()
    proc.stdin.write(b'4\n')
    proc.stdout.read()
    proc.stdin.write(b'\n')
    proc.stdout.read()
    proc.stdin.write(b'y\n')
    proc.stdout.read()
    proc.stdin.write(b'123\n')
    proc.stdout.read()
        print("done")
    

    这不起作用。没有输出,它似乎没有响应“stdin.write”或从标准输出输出任何东西,为什么这么烦人,我只想自动化一些控制台响应。

    也许我没有看到什么,也许 TerrariaServer.exe 有不同的响应或什么。

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2016-07-15
      • 1970-01-01
      • 2017-09-08
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多