2

在这里使用 Python 的第一次体验,我希望能够以当前时间/日期作为行中的第一项打印出一些文本。

到目前为止,这是我能做的,但我的语法似乎不正确,有人可以纠正我吗?

import socket
import sys
import time
import datetime

remote_host = "127.0.0.1"

now = datetime.datetime.now()

for remote_port in [9002,8080]:
        now_text = now.strftime("%Y-%m-%d %H:%M")
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(60)
        try:
                sock.connect((remote_host, remote_port))
        except Exception,e:
                print "%d %d closed " % now_text remote_port
        else:
                print  "%d %d open" % now_text remote_port
        sock.close()

亲切的问候

4

4 回答 4

5

我想你正在寻找类似的东西

print "%d %d closed" % (now_text, remote_port)

以供将来参考,这是在 Python 3 中执行此操作的一种方法:

print("{0} {1} closed".format(now_text, remote_port))

.format()方法是在 Python 2.6 中引入的。

于 2010-12-24T09:31:46.280 回答
1

两个可能的错误(第二个确定):

  1. Exception,e需要替换为Exception as e(取决于 Python 版本)。
  2. % 运算符需要一个元组参数:"%d %d closed" % (a, b).
于 2010-12-24T09:33:39.060 回答
0
>>> print "%s %d closed " % (now_text,remote_port)
2011-03-15 14:46 9002 closed
于 2011-03-15T19:48:42.400 回答
0

这是我的看法:

#the code below will print the date and time on separate lines.

from datetime import datetime
now =datetime.now()

print('%s/%s/%s' %(now.month,now.day,now.year))
print('%s:%s:%s' %(now.hour,now.minute,now.second))
于 2017-05-20T10:29:54.093 回答