【问题标题】:Python socket server, is there a way for user to input the port on terminal?Python套接字服务器,用户有没有办法在终端上输入端口?
【发布时间】:2019-05-27 02:09:55
【问题描述】:

我有一个任务要我创建一个套接字程序,该程序必须用户在终端上输入端口号。因此,与其在程序中定义端口,不如通过以下方式定义端口: $ python3 socket_program.py &

有没有办法做到这一点?

【问题讨论】:

  • “输入”这个词已经是一个很好的提示(至少对于 Python 3.x)。

标签: python sockets terminal


【解决方案1】:

是的,使用 sys 访问传递给脚本的参数。这是一个将第一个参数传递给脚本并将其分配给名为 port 的变量的示例。

import sys
if len(sys.argv) > 1:
  port = int(sys.argv[1])
else:
  port = 3000

【讨论】:

  • 谢谢!出于某种原因,它需要我将其转换为 str 然后 int。 “端口 = int(str(sys.argv[1]))”
猜你喜欢
  • 2019-01-31
  • 1970-01-01
  • 2018-03-19
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多