Reputation: 16428
First experiences with Python here, I want to be able to print out some text with the current time/date as the first item on the line.
This is what I've been able to cook up so far, but it appears I'm syntactically incorrect, can someone please correct me?
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()
Kind regards
Upvotes: 2
Views: 5738
Reputation: 1
This is my take:
#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))
Upvotes: 0
Reputation: 1091
>>> print "%s %d closed " % (now_text,remote_port)
2011-03-15 14:46 9002 closed
Upvotes: 0
Reputation: 185862
Two possible errors (the second one definite):
Exception,e
needs to be replaced by Exception as e
(depending on the Python version)."%d %d closed" % (a, b)
.Upvotes: 1
Reputation: 993163
I think you're looking for something like
print "%d %d closed" % (now_text, remote_port)
For future reference, here's one way to do that in Python 3:
print("{0} {1} closed".format(now_text, remote_port))
The .format()
method was introduced in Python 2.6.
Upvotes: 5