'How can I download and execute a python script in a thread? (Python)

context: new to threading here, please don't bully me for being incredibly stupid.

I'm trying to create a python script that downloads and executes another python script from the internet. The script downloaded from the internet will need to import some libraries, so I'm having trouble finding a good way to get that done. Right now, the code seems to work before I implement threading, but not after. I've also tried implementing a similar solution with asyncio, but it resulted in the same error. My suspicion at the moment is that the variable scope is getting messed up somewhere, but I don't know where and couldn't find any relevant information about it on the internet.

Also note: the libraries the downloaded script will import and use (once it's fixed) are the following: socket, subprocess, time, and os

My code:

import requests
import threading

def toBeThreaded(someScript):
    exec(someScript)


def func():
    # do some stuff
    someScript = requests.get('https://mywebsite.com/pythonscript.py').content
    download_thread = threading.Thread(target=toBeThreaded, name="Placeholder", args=[someScript])
    download_thread.start()
    
    # continue doing stuff

func()

print("test")

Output:

Exception in thread Placeholder:
Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\Me\coding\scriptDownlaoder.py", line 5, in toBeThreaded
    exec(someScript)
  File "<string>", line 77, in <module>
  File "<string>", line 76, in main
NameError: name 'connect' is not defined
PS C:\Users\Me\coding>

My code without threading (working):


import requests

exec(requests.get('https://mywebsite.com/pythonscript.py').content)

print("Success!")

Output:

Success!

And finally, the script that I'm trying to download and execute:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # start a socket object 's' 
s.connect(('0.0.0.0', 9001)) # connect to machine

# working with socket in here

s.close()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source