Install Python script requirements
!!! Use this at your own risk. Fiddling with user's packages is scary business !!!

You can monkey-patch the builtin import statement and upon encountering ModuleNotFoundError install whatever dependency is missing. Here is a small example for a script.py. You can of course extend this to feature multiple files or dynamically use the file given as input.

import builtins
import pip
old_import = __import__

def my_import(name, globals=None, locals=None, fromlist=(), level=0):
    if globals["__name__"] == "script":
        try:
            return_args = old_import(name, globals=globals, locals=locals, 
                                    fromlist=fromlist, level=level)
        except ModuleNotFoundError:
            builtins.__import__, temp = old_import, builtins.__import__
            pipcode = pip.main(['install', name])
            if pipcode != 0:
                builtins.__import__ = temp
                raise
            else:
                return_args = old_import(name, globals=globals, locals=locals, 
                                    fromlist=fromlist, level=level)
                builtins.__import__ = temp
    else:
        return_args = old_import(name, globals=globals, locals=locals, 
                                fromlist=fromlist, level=level)

    return return_args

builtins.__import__ = my_import

import script


and the script.py is your custom script:

import os
from time import time

import argh  # this should be installed

print(time())


Note: People sometimes do things like:

try:
    import optional_module
except ImportError:
    pass  # optional all cool


Above code patches import itself. If you remove the if that limits install powers to script you allow recursive installation for everything that is imported. Ever. Even if it is an optional dependency for a 4th level dependency test case of script pip will try to install it.