Python 'A bytes like object is required' 即使在编码后写入标准输入时
Python 'A bytes like object is required' when writing to stdin even after encoding
我的代码是:
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)
它总是,总是说需要一个类似字节的对象,即使我打印它并且它清楚地显示它是字节格式的,而且即使在极少数情况下我已经让它工作了,它仍然什么都不做.
为什么会这样??
print
函数计算其输入的字符串表示形式,添加换行符,并将其输出到字符流。如果您有二进制流(如进程的 stdin
),请使用 write
:
print(command) # This will output "b'USER INPUT'" (with a leading b')
process.stdin.write(command + b'\n')
我的代码是:
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)
它总是,总是说需要一个类似字节的对象,即使我打印它并且它清楚地显示它是字节格式的,而且即使在极少数情况下我已经让它工作了,它仍然什么都不做.
为什么会这样??
print
函数计算其输入的字符串表示形式,添加换行符,并将其输出到字符流。如果您有二进制流(如进程的 stdin
),请使用 write
:
print(command) # This will output "b'USER INPUT'" (with a leading b')
process.stdin.write(command + b'\n')