【问题标题】:Basic shell with Python. How to change directory?带有 Python 的基本 shell。如何更改目录?
【发布时间】:2015-08-24 17:24:58
【问题描述】:

服务器端代码,处理客户端发送的数据。

#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)

客户端代码,发送数据(命令)并打印结果

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

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

当我尝试使用诸如“cd ..”之类的命令时,它没有成功,因为据我所知,它会将目录更改为子进程。有没有办法使用客户端更改父目录?

【问题讨论】:

  • 你可以用 os.chdir(path) 改变工作目录
  • 你应该知道一些shell命令,比如cd是内置的,但大多数是与shell没有连接的外部程序。外部命令可以使用subprocess 运行,内置命令不能。因此,如果您正在编写 shell,请确定哪些是内置的。要在 bash 中找出现有的,请使用 type cdtype kill 等。您可能需要一个字典,其中键是内置函数的名称,值是每个内置函数的函数。
  • 是的。正如 Luciano 所建议的,我真的很喜欢“自定义命令”的想法。根据我的需要,如果我不能拥有它们,我会创建它们。

标签: python windows shell


【解决方案1】:

是的,你是对的。 "cd" 将改变子进程目录。

但是,您可以在执行之前分析命令并应用一些特殊行为。

小心,检测到丑陋的代码。

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

【讨论】:

  • 因为这是 Windows 并且 data 是 UTF-8 编码的,所以应该首先将其解码为 unicode 以使用文件系统的宽字符 API。否则它仅限于 ASCII。
猜你喜欢
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 2012-01-05
  • 2011-04-16
  • 1970-01-01
相关资源
最近更新 更多