通过python运行TerrariaServer

通过python运行TerrariaServer,python,Python,我遇到的第一个问题是,我不知道如何响应命令提示符 bat_location = "F:/SteamLibrary/steamapps/common/Terraria" os.chdir(bat_location) os.system("TerrariaServer.exe -steam -lobby friends -config serverconfig.txt") 所有这些都是可行的,但当我想响应命令提示符时,它会询问我要运行哪个世界,世界会被1-n个世界的数字索引,我不知道如何响应 我已

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

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")
这似乎没有任何作用,我也尝试了很多子流程,但我显然迷路了

任何帮助都是必要的

第1条编辑:

嗯,现在我已经试过了:

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')
而它所做的一切,我猜是由它的反应,它只是一圈又一圈

第2条编辑:


我将关闭此文件并启动一个新线程,因为我的问题完全源于原始问题。

从您最近的几条评论中,我意识到您与Popen之间存在的问题。当您传递stdout=PIPE和stderr=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等,但是您可能必须小心如何从阻塞读取函数中获取数据。

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

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。从stdout写入或输出任何内容,为什么这么烦人,我只想自动化一些控制台响应


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

看看答案,你几乎肯定想使用,而不是os.system.ok,所以我尝试使用这个:proc=subprocess.Popen['cd F:/SteamLibrary/steamapps/common/Terraria','TerrariaServer.exe-steam-Lobble friends-config serverconfig.txt'],stdout=PIPE,stdin=PIPE,stderr=stdout,但它只是抛出了一个错误[WinError 2]系统找不到指定的文件。我是否缺少什么?它正在尝试运行两个不同的命令;子流程函数每个只运行一个命令。若要设置工作目录,请使用cwd关键字参数。我何时在TerrariaServer.exe等之前或之后指定它?cwd必须在任何位置之后作为关键字参数指定但是,您可能希望使用完整路径来运行程序,该路径可能是F:/streamlibrary/streamapps/common/terria/terria.exe。