This is a pure Python solution, as compared to the other answer which requires Bash.
First, you can get the raw content of the Pastebin link using requests
module's requests.content
:
import requests
pastebin_raw_link = 'https://pastebin.com/raw/xxxxxxxx'
response = requests.get(pastebin_raw_link)
source_code = response.content
print(source_code.decode('utf-8'))
That should print out the same contents as the "raw" tab of Pastebin

Next, you can run source_code
by:
Option 1: Calling exec
on it
exec(source_code)
This is generally the accepted answer from How do I execute a string containing Python code in Python? It is also generally considered as unsafe, as discussed in posts such as Why should exec() and eval() be avoided? Make sure you really really trust that Pastebin link.
Option 2: Writing it to a tempfile.NamedTemporaryFile()
then using importlib
to import Python modules directly from a source file:
import importlib.util
import sys
import tempfile
with tempfile.NamedTemporaryFile(suffix='.py') as source_code_file:
# Should print out something like '/var/folders/zb/x14l5gln1b762gjz1bn63b1sxgm4kc/T/tmp3jjzzpwf.py' depending on the OS
print(source_code_file.name)
source_code_file.write(source_code)
source_code_file.flush()
# From Python docs recipe on "Importing a source file directly"
module_name = 'can_be_any_valid_python_module_name'
spec = importlib.util.spec_from_file_location(module_name, source_code_file.name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
This is similar to just manually copying the contents of the Pastebin link, pasting it to some file (ex. 'test.py') in the same directory, and then importing it as import test
, which executes the contents of the file.
It is also possible to not use tempfile.NamedTemporaryFile
, but then you'll have to manually delete the files you create. The tempfile
module already does that for you: "the file is deleted as soon as it is closed".
Also, the nice thing about importing it as a module, is that it acts like any other Python module. Meaning, for example, your Pastebin link declares some variables or methods, then you can do:
module.some_variable
module.call_some_method()