【发布时间】:2021-01-25 13:25:41
【问题描述】:
我正在用 Python3 中的远程 shell 实用程序制作一个程序,使用套接字和子进程。到目前为止一切正常,但我遇到了一个我找不到解决方案的问题。这是我的服务器脚本上的代码,它执行从客户端接收到的命令:
process = subprocess.Popen(client_buffer.decode('utf-8').split(), stdout = subprocess.PIPE) # Creating a process
while True: # Reading and sending the stdout from the process in realtime
shell_output = process.stdout.readline() # Read a line from stdout
return_code = process.poll()
print(shell_output)
print(return_code)
if shell_output.decode('utf-8') == '' and return_code is not None:
#print("Process execution complete. Sending user prefix")
send(client, ("<#" + color.user + getpass.getuser() + color.endc + "@" + color.dir + cwd() + color.endc + ">").encode('utf-8'))
break
elif shell_output:
# Process execution incomplete, signaling to client with code 2
send(client, int_to_bytes(2))
# And sending the next line of stdout
send(client, shell_output)
一切正常,我很满意,但有一个限制我不知道如何消除。 也就是说,我可以轻松地向服务器提供带有参数的命令,服务器将执行它并将输出发回,这很好,但是如果由命令启动的程序要求额外的输入(例如“(y / n )" 问题)在流程执行结束之前(执行中),我不知道如何向流程提供输入。
我可以用 subprocess.Popen() 做到这一点吗?任何线索都会有所帮助,我提前感谢您。我忘了补充,这个程序是用来在 Linux 中使用的。
P.S 任何我在代码示例中没有提供的定义/声明的函数和变量都无关紧要,但是可以在我的github 上找到该项目,以防有人想查看更多代码 em>
【问题讨论】:
标签: python python-3.x subprocess