You are setting noncelist
to an empty list each time in the function so obviously you only keep one value in it that you append on the next line, you would need to declare the list outside the function and pass the list in as an argument, using a class may be a better approach making the list an attribute.
import blocktrail, time
class Bit():
def __init__(self):
self.nonce_list = []
def run(self):
while True:
client = blocktrail.APIClient(api_key="x", api_secret="x", network="BTC", testnet=False)
address = client.address('x')
latest_block = client.block_latest()
nonce = latest_block['nonce']
blockhash = latest_block['hash']
nonce_str = str(nonce)
self.nonce_list.append(nonce_str)
print(self.nonce_list)
time.sleep(60)
Bit().run()
If you want to continually run the code you should probably daemonize the process, also the function continually calling itself is really not a good idea
If you are going to use a function, pass the list in and loop in the function just calling it once:
def code(noncelist):
while True:
client = blocktrail.APIClient(api_key="x", api_secret="x", network="BTC", testnet=False)
address = client.address('x')
latest_block = client.block_latest()
nonce = latest_block['nonce']
blockhash = latest_block['hash']
print(nonce)
noncestr = str(nonce)
noncelist.append(noncestr)
print(noncelist)
time.sleep(60)
code([])
If you just want unique nonce's use a set to keep track of what has been added, I made created an example of using a class with multiple attributes, you will need to catch more possible exceptions:
import blocktrail, time
class Bit():
def __init__(self, key, secret, net, retry_fail=1, update=60,max_fail=10):
self.nonce_list = []
self.seen = set()
self.key = key
self.secret = secret
self.net = net
self.key = key
self.retry_fail = retry_fail
self.update = update
self.max_fails = max_fail
def connect(self):
return blocktrail.APIClient(api_key=self.key, api_secret=self.secret, network=self.net, testnet=False)
def run(self):
while True:
if not self.max_fails:
break
try:
client = self.connect()
latest_block = client.block_latest()
except blocktrail.exceptions.MissingEndpoint as e:
self.max_fails -= 1
print("Error: {}\n sleeping for {} second(s) before retrying".format(e.msg, self.retry_fail))
time.sleep(self.retry_fail)
continue
nonce = latest_block['nonce']
if nonce not in self.seen:
self.nonce_list.append(nonce)
self.seen.add(nonce)
print(self.nonce_list)
time.sleep(self.update)
The key,secret and net are required, you can pass the other or use the defaults:
Bit("key","secret", "net").run()