I’m trying to run multiple instances of a class concurrently in a single Python application, simulating the effect of having separate terminals running each class independently. My goal is to have each instance operate independently and not block each other. I’m using asyncio for concurrency.
Here’s a simplified version of what I’m trying to achieve:
import os
from operations import Operations # Assuming this is my custom class
# Load environment variables
os.environ['ADDRESS1'] = 'address1'
os.environ['PRIVATE_KEY1'] = 'private_key1'
os.environ['ADDRESS2'] = 'address2'
os.environ['PRIVATE_KEY2'] = 'private_key2'
class Operations:
def __init__(self, address, private_key):
self.address = address
self.private_key = private_key
async def run(self):
while True:
print(f"Running operations for {self.address}")
await do_other_thing()
await asyncio.sleep(1)
# Initialize instances with different addresses and private keys
instances = [
Operations(os.getenv('ADDRESS1'), os.getenv('PRIVATE_KEY1')),
Operations(os.getenv('ADDRESS2'), os.getenv('PRIVATE_KEY2'))
]
async def run_instance(instance):
await instance.run()
async def main():
tasks = [asyncio.create_task(run_instance(instance)) for instance in instances]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())