简体   繁体   English

Python的基本外壳。 如何更改目录?

[英]Basic shell with Python. How to change directory?

Server-side code, which handles the client's sent data. 服务器端代码,用于处理客户端的已发送数据。

#receiving data
data = client.recv(1024)
# if it's quit, then break out and close socket
if data.decode("UTF-8") == "quit": break
# do shell command
proc = subprocess.Popen(data.decode("UTF-8"), shell=True, stdout=subprocess.PIPE, \
       stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# read output
stdout_value = proc.stdout.read() + proc.stderr.read()
valid = "done"
if stdout_value.decode(sys.stdout.encoding, errors="ignore") == "":
    client.send(valid.encode("utf-8")) # for commands like "C:", which print nothing
# send output
client.send(stdout_value)

Client-side code, which sends data (commands) and prints the results 客户端代码,用于发送数据(命令)并打印结果

reply = input()
client.send(reply.encode("UTF-8"))

receive = client.recv(4096)
print(receive.decode(sys.stdout.encoding, errors="ignore")

When I try to use a command such as "cd ..", it doesn't succeed because as far as I know, it changes directory to the child process. 当我尝试使用“ cd ..”之类的命令时,它不会成功,因为据我所知,它将目录更改为子进程。 Is there any way to change the parent's directory, using the client? 有什么办法可以使用客户端更改父目录?

Yes, you're right. 你是对的。 "cd" will change the child process dir. “ cd”将更改子进程目录。

But, you can analyse the command before execute and apply some special behavior. 但是,您可以在执行之前分析命令并应用一些特殊行为。

Beware, ugly code detected. 当心,检测到难看的代码。

from os import chdir
...
if data.startswith('cd '):
    chdir(data[3:])  # Don't execute with Popen
else:
    proc = .....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM