Inconsistent sockets output - python

I've tried asking before and got a snarky response so I thought I'd try again, with a new problem that I've more recently run into. Basically, the same code is used for all 4 clients, and the same thing is being sent to each of them using a for loop. However, sometimes the output is different on certain clients and this changes every time I run the code. The client where the error(s) occur is also different. In the client script:
def receieve_message():
while True:
command = client.recv(2048).decode(FORMAT)
if command == "VOTE":
round_one_vote = input("Who would you like to remove: ")
message = ("VOTE1 "+round_one_vote)
send(message)
else:
print(command)
I am sending in either the word VOTE from the server or a string of text. If it is a string of text it should print it out to the client. If it is VOTE it will take an input. I am sending the data from the server like this:
for client in clients:
client.send("VOTE".encode(FORMAT))
When I've just run it, 3 out of 4 clients begin the input check, however the first client prints out VOTE, which should not be happening. When I run it a second, time the first two print out VOTE. There doesn't seem to be a pattern.
Additionally, there are random line breaks sometimes, also arbritarily

Related

How to use the most recently printed line as an input?

I am trying to create a Twitter bot that posts a random line from a text file. I have gone as far as generating the random lines, which print one at a time, and giving the bot access to my Twitter app, but I can't for the life of me figure out how to use a printed line as a status.
I am using Tweepy. My understanding is that I need to use api.update_status(status=X), but I don't know what X needs to be for the status to match the most recently printed line.
This is the relevant section of what I have so far:
from random import choice
x = 1
while True:
file = open('quotes.txt')
content = file.read()
lines = content.splitlines()
print(choice(lines))
api.update_status(status=(choice(lines)))
time.sleep(3600)
The bot is accessing Twitter no problem. It is currently posting another random quote generated by (choice(lines)), but I'd like it to match what prints immediately before.
I may not fully understand your question, but from the very top, where it says, "How to use the most recently printed line as an input", I think I can answer that. Whenever you use the print() command, store the argument into a string variable that overwrites its last value. Then it saves the last printed value.
Instead of directly printing a choice:
print(choice(lines))
create a new variable and use it in your print() and your api.update_status():
selected_quote = choice(lines)
print(selected_quote)
api.update_status(status=selected_quote)

Program doesn't append file using variables, but no error message appears

Using Python 3.4.2
I'm working on a quiz system using python. Though it hasn't been efficient, it has been working till now.
Currently, I have a certain user log in, take a quiz, and the results of the quiz get saved to a file for that users results. I tried adding in so that it also saves to a file specific to the subject being tested, but that's where the problem appears.
user_score = str(user_score)
user_score_percentage_str = str(user_score_percentage)
q = open('user '+(username)+' results.txt','a')
q.write(test_choice)
q.write('\n')
q.write(user_score+'/5')
q.write('\n')
q.write(user_score_percentage_str)
q.write('\n')
q.write(user_grade)
q.write('\n')
q.close()
fgh = open(test_choice+'results.txt' ,'a')
fgh.write(username)
fgh.write('\n')
fgh.write(user_score_percentage_str)
fgh.write('\n')
fgh.close
print("Your result is: ", user_score , "which is ", user_score_percentage,"%")
print("Meaning your grade is: ", user_grade)
Start()
Everything for q works (this saves to the results of the user)
However, once it comes to the fgh, the thing doesn't work at all. I receive no error message, however when I go the file, nothing ever appears.
The variables used in the fgh section:
test_choice this should work, since it worked for the q section
username, this should also work since it worked for the q section
user_score_percentage_str and this, once more, should work since it worked for the q section.
I receive no errors, and the code itself doesn't break as it then correctly goes on to print out the last lines and return to Start().
What I would have expected in the file is to be something like:
TestUsername123
80
But instead, the file in question remains blank, leading me to believe there must be something I'm missing regarding working the file.
(Note, I know this code is unefficient, but except this one part it all worked.)
Also, apologies if there's problem with my question layout, it's my first time asking a question.
And as MooingRawr kindly pointed out, it was indeed me being blind.
I forgot the () after the fgh.close.
Problem solved.

Python how do I break out of blocking generator that is waiting for server response?

So I have this code that would take user speech and transcribe it into text using Google Cloud Speech API. It is written based on this example from Google: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_streaming_mic.py
I wanted to add an error handler that would stop the transcription process whenever there's an internet connection problem. I create a connection monitor thread that check internet connection every few seconds and will set a flag isConnectionError = True.
I manage to stop the audio recording generator process but I can't stop another generator process that block and waits for server to send response message:
def listen_print_loop(responses):
"""Iterates through server responses and prints them.
The responses passed is a generator that will block until a response
is provided by the server.
Each response may contain multiple results, and each result may contain
multiple alternatives; for details, see <url removed>. Here we
print only the transcription for the top alternative of the top result.
In this case, responses are provided for interim results as well. If the
response is an interim one, print a line feed at the end of it, to allow
the next result to overwrite it, until the response is a final one. For the
final one, print a newline to preserve the finalized transcription.
"""
num_chars_printed = 0
for response in responses:
if not response.results:
continue
# The `results` list is consecutive. For streaming, we only care about
# the first result being considered, since once it's `is_final`, it
# moves on to considering the next utterance.
result = response.results[0]
if not result.alternatives:
continue
# Display the transcription of the top alternative.
transcript = result.alternatives[0].transcript
# Display interim results, but with a carriage return at the end of the
# line, so subsequent lines will overwrite them.
#
# If the previous result was longer than this one, we need to print
# some extra spaces to overwrite the previous result
overwrite_chars = ' ' * (num_chars_printed - len(transcript))
if not result.is_final:
sys.stdout.write(transcript + overwrite_chars + '\r')
sys.stdout.flush()
num_chars_printed = len(transcript)
else:
print(transcript + overwrite_chars)
# Exit recognition if any of the transcribed phrases could be
# one of our keywords.
if re.search(r'\b(exit|quit)\b', transcript, re.I):
print('Exiting..')
break
num_chars_printed = 0
We achieved the same through websockets on listeners and emitters for connection where Speech-to-text hapens from web page to Java service
As suggested by Kenny, I just run the generator in a separate thread. Works flawlessly

Python smtplib sending mail using docmd

I currently have an smtplib client using sendmail. I need to trap the message id given to the sent message by the receiving server - and from what I've read here I need to use smtplib's docmd command. What I've worked out so far is fairly easy:
import smtplib
svr = smtplib.SMTP("localhost",26)
r = svr.docmd("ehlo", "me")
r = svr.docmd("mail from:","me#home.com")
r = svr.docmd("rcpt to:","you#work.com")
r = svr.docmd("data","")
But now when I try to do svr.docmd("send","Hello there") it just hangs? Similarly, I assume I should do r = svr.docmd("send",".") to send the terminating "." character to send the mail, and get the server response (in theory including msg id!) as part of the returned tuple?
Would really appreciate it if someone could point me at where I'm going wrong in these final steps?
Or am I completely misunderstanding - is using docmd NOT the way to get the server response when the mail is sent? If I am wrong, what should I be doing instead?
smtplibmodule cannot work like that. It is a higher level library and you should not try to send simple mail with docmd. docmd only helps to pass special commands. You should simply use :
svr.sendmail('me#home', 'you#work', 'msg')
If you really want to do it the hard way, you should send all the data in only single docmd :
...
r = svr.docmd("data")
r = svr.docmd("line 1\r\nline 2\r\n.\r\n")
That way it a a complete command that receives its SMTP response
Edit :
The return of low-level commands is the content of the SMTP response. The RFC 2821 specifies that this replies consist in a 3 digit number followed by an textual explaination. It can be multiline if the number is followed by a -. But all that is hidden from you by smtplib module. The main point of interest if you use low level commands is first digit from the number :
1yz Positive Preliminary reply
2yz Positive Completion reply
3yz Positive Intermediate reply
4yz Transient Negative Completion reply
5yz Permanent Negative Completion reply
If it is 4 or 5 the command was rejected, 1,2, or 3 it was successful
If you use directly sendmail command, if you do not get an exception, the mail was successfuly received by the server and accepted for at least on recipient. The return value is a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server (extract from the module documentation).
I advice you to use the sendmail command unless you want to learn the SMTP protocol or have other special requirement.

Checking if A follows B on twitter using Tweepy/Python

I have a list of a few thousand twitter ids and I would like to check who follows who in this network.
I used Tweepy to get the accounts using something like:
ids = {}
for i in list_of_accounts:
for page in tweepy.Cursor(api.followers_ids, screen_name=i).pages():
ids[i]=page
time.sleep(60)
The values in the dictionary ids form the network I would like to analyze. If I try to get the complete list of followers for each id (to compare to the list of users in the network) I run into two problems.
The first is that I may not have permission to see the user's followers - that's okay and I can skip those - but they stop my program. This is the case with the following code:
connections = {}
for x in user_ids:
l=[]
for page in tweepy.Cursor(api.followers_ids, user_id=x).pages():
l.append(page)
connections[x]=l
The second is that I have no way of telling when my program will need to sleep to avoid the rate-limit. If I put a 60 second wait after every page in this query - my program would take too long to run.
I tried to find a simple 'exists_friendship' command that might get around these issues in a simpler way - but I only find things that became obsolete with the change to API 1.1. I am open to using other packages for Python. Thanks.
if api.exists_friendship(userid_a, userid_b):
print "a follows b"
else:
print "a doesn't follow b, check separately if b follows a"

Categories

Resources