如何更改命令行以执行

时间:2017-05-01 03:14:09

标签: python command-line execution

我为聊天客户端和聊天服务器编写了一个简单的代码(客户端的单独代码和服务器的代码)。我的服务器当前使用命令行执行

python chatserve.py <port number>

刚刚发现类要求是程序以以下命令行开头:

./chatclient <portnumber>

我如何转换?我非常感谢任何提示/帮助。谢谢!

(为了澄清任何混淆,我的聊天客户端的执行在其命令行中也需要./chatclient,但由于该部分代码是用C语言编写的,因此我能够弄清楚如何获取它用特定的命令行执行。不幸的是,我不熟悉Python。)

以下是代码:

#!/bin/python

from socket import *
import sys

#initiate chat with client
def chat(connectionsocket, clientname, username):
    to_send = ""
    while 1:    # continue chat until break
        # get characters from the user
        received = connectionsocket.recv(501)[0:-1]

        # if we received nothing, print close message and break
        if received == "":
            print "Closed connection.  Wait for new connection..."
            break

        # print client username and message
        print "{}> {}".format(clientname, received)

        # get server input and send to client
        to_send = ""
        while len(to_send) == 0 or len(to_send) > 500:
            to_send = raw_input("{}> ".format(username))

        # special "\quit" message 
        if to_send == "\quit":
            print "Closed connection.  Wait for new connection..."
            break
        connectionsocket.send(to_send)

#initiate handshake with client
def handshake(connectionsocket, username):
    # get the client username
    clientname = connectionsocket.recv(1024)

    # send server username to the client
    connectionsocket.send(username)

    return clientname

#execution
if __name__ == "__main__":

    # If wrong number of arguments, print error message and exit
    if len(sys.argv) != 2:
        print "Error: no port number input"
        exit(1)

    # get port number and create TCP socket
    serverport = sys.argv[1]
    serversocket = socket(AF_INET, SOCK_STREAM)

    # bind socket to port
    serversocket.bind(('', int(serverport)))

    # listen on port for incoming messages
    serversocket.listen(1)

    # get username
    username = ""
    while len(username) == 0 or len(username) > 10:
        username = raw_input("Enter username (10 characters or less): ")
        print "Receiving incoming messages..."

    # continue receiving incoming messages until close
    while 1:
        # create new socket for incoming connection
        connectionsocket, address = serversocket.accept()

        # print connection message 
        print "Receiving connection on address {}".format(address)

        # initiate handshake and chat with incoming connection
        chat(connectionsocket, handshake(connectionsocket, username),     username)

        # close connection
        connectionsocket.close()

1 个答案:

答案 0 :(得分:1)

请按照以下步骤操作:

  1. 将文件名重命名为:chatserve
  2. 在代码的第一行添加以下命令:#!/usr/bin/python#!/usr/bin/python2#!/usr/bin/python3
  3. 允许他执行:chmod +x chatserve