使用python n显示客户端当前目录中的文件和所有目录

2024-06-14 10:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description hereenter image description here

在客户端文件的当前目录下显示文件时遇到问题。 并显示客户端文件当前目录下的所有目录和子目录

我应该在客户端的命令提示符中显示它,如上图所示

请帮我输入这个代码。多谢各位

到目前为止,我掌握的代码如下:

server.py:

import socket
import threading
import os

HOST = "localhost"      
PORT = 5551

def setpath(curdir, np, conn):
    print("setting new path")
    print("from: ", curdir)
    print("to: " , np)

    m = "New Path: " + np

    conn.send(m.encode('utf-8'))

def showfiles(p, conn):
    ffound = "Files found under: " + p + "\n"
    conn.send(ffound.encode('utf-8'))
    for (path, dirlist, filelist) in os.walk(p):
       for f in filelist:
            print(f)
            f = f + "\n"
            conn.send(f.encode('utf-8'))

def showdir(p, conn):
    dfound = "Directories found under: " + p + "\n"
    conn.send(dfound.encode('utf-8'))
    for (path, dirlist, filelist) in os.walk(p):
        for d in dirlist:
            print(os.path.join(path, d))
            dr = os.path.join(path, d) + "\n"
            conn.send(dr.encode('utf-8'))

def clientsocket():
    s.listen()
    (conn, addr) = s.accept() 

    FCL = []
    while True:
        fromClient = conn.recv(1024).decode('utf-8')
        FCL.append(fromClient)
        if fromClient == 's':
            fc = conn.recv(1024).decode('utf-8')
            setpath(FCL[0], fc, conn)
            FCL.pop()
        if fromClient == 'f' :
            showfiles(FCL[0], conn)
            FCL.pop()
        if fromClient == 'd' :
            showdir(FCL[0], conn)
            FCL.pop()
        if fromClient == 'q':
            break

with socket.socket() as s :
    s.bind((HOST, PORT))
    print("Server hostname:", HOST, "port:", PORT)

    try :
        s.settimeout(10)        # set timer to time out after 3 seconds
        threads= []
        t = threading.Thread(target = clientsocket)
        threads.append(t)
        t.start()
        for th in threads :
            th.join()

    except socket.timeout :    
        print("Caught Time-Out! No Client Connected.") 

client1.py

import socket
import os

HOST = '127.0.0.1'
PORT = 5551

def userinput(p):

    m = input("s: set path \nf: show files \nd: show dirs \nq: quit \nEnter Choice: ")
    while m not in ['s','f','d','q']:
        m = input("s: set path \nf: show files \nd: show dirs \nq: quit \nEnter Choice: ")

s.send(m.encode('utf-8'))

    if m == 's':
        newpath= input("Enter path, starting from current directory: ")
        s.send(newpath.encode('utf-8'))

    return m

def display():
    print()

with socket.socket() as s :
    s.connect((HOST, PORT))
    print("Client connect to:", HOST, "port:", PORT)
    p = os.getcwd()
    s.send(p.encode('utf-8'))
    print("Current Directory:", p)
    mesg = userinput(p)
    while mesg != 'q':
        fromServer = s.recv(1024).decode('utf-8')
        print(fromServer)
        mesg = userinput(p)

Tags: pathinimportsendhostosportdef