ThreadPoolExecutor has a problem when I run it, but it doesn't send any response, even though I've already written print in the code

Question:

why when i run it nothing appears?

from concurrent.futures import ThreadPoolExecutor
import os, sys, json, requests, hashlib

G = '33[1;32m'
R = '33[1;91m'
W = '33[1;97m'
B = '33[1;94m'

def saekomatsushita(tofu):
    N = 7
    token = ''.join(random.choices(string.ascii_letters, k=N))
    print(tofu + ' - ' + token)

with ThreadPoolExecutor(max_workers=30) as sh:
    e = open('j.txt').read()
    _ = [sh.submit(saekomatsushita, e)]

Please help, I’m very tired because of this one problem

Asked By: jamesomen

||

Answers:

You didn’t import the string and random modules. This will cause an error and your subthread will terminate. You don’t see any error message because ThreadPoolExecutor threads will not print any exception message when any exception occur. Because your saekomatsushita() function will be executed (in source code of ThreadPoolExecutor) like below ;

try:
    saekomatsushita()

except BaseException as exc:
    # something

To solve this, you can use try except block in your subthread (in saekomatsushita func), or you can call result() method of future object.

Here is the description of result(timeout=None) method in the doc:

result(timeout=None) :

Return the value returned by the call. If the call hasn’t yet
completed then this method will wait up to timeout seconds. If the
call hasn’t completed in timeout seconds, then a
concurrent.futures.TimeoutError will be raised. timeout can be an int
or float. If timeout is not specified or None, there is no limit to
the wait time.

If the future is cancelled before completing then CancelledError will be raised.

If the call raised an exception, this method will raise the same exception.

Here is the first solution ;

from concurrent.futures import ThreadPoolExecutor
import os, sys, json, requests, hashlib

G = '33[1;32m'
R = '33[1;91m'
W = '33[1;97m'
B = '33[1;94m'

def saekomatsushita(tofu):
    try:
        N = 7
        token = ''.join(random.choices(string.ascii_letters, k=N))
        print(tofu + ' - ' + token)
    except Exception as e:
        print("error: {}".format(e))

with ThreadPoolExecutor(max_workers=30) as sh:
    e = open('j.txt').read()
    _ = [sh.submit(saekomatsushita, e)]

Here is the second solution :

from concurrent.futures import ThreadPoolExecutor
import os, sys, json, requests, hashlib

G = '33[1;32m'
R = '33[1;91m'
W = '33[1;97m'
B = '33[1;94m'
def saekomatsushita(tofu):
    N = 7
    token = ''.join(random.choices(string.ascii_letters, k=N))
    print(tofu + ' - ' + token)

with ThreadPoolExecutor(max_workers=30) as sh:
    e = open('j.txt').read()

    future = sh.submit(saekomatsushita, e)
    future.result()
Answered By: Veysel Olgun