首页 > 解决方案 > 即使在编码后写入标准输入时,Python 'A bytes like object is required'

问题描述

我的代码是:

import subprocess, os

#just write the command to the input stream
process = None
minecraft_dir = '.'
executable = 'java -jar server.jar'
while True:
    command=input('cmd: ').encode()
    if command==(b"start"):
            os.chdir(minecraft_dir)
            process = subprocess.Popen(executable, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            print("Server started.")
    else:
            print(command)
            print(command, file=process.stdin)

它总是说需要一个类似字节的对象,即使我打印它并且它清楚地显示它是字节格式,即使我很少让它工作,它仍然什么都不做。

为什么会这样??

标签: javapythonminecraft

解决方案


print函数计算其输入的字符串表示形式,添加换行符,并将其输出到字符流。如果您有二进制流(例如stdin您的进程),请使用write

print(command) # This will output "b'USER INPUT'" (with a leading b')
process.stdin.write(command + b'\n')

推荐阅读