1 回答
TA贡献1863条经验 获得超2个赞
我相信以下应该达到您的期望:
#!/usr/bin/env python3
import pathlib
import string
import subprocess
import tempfile
import venv
SCRIPT_TEMPLATE = '''\
#!${venv_executable}
import requests
print(requests)
'''
class EnvBuilder(venv.EnvBuilder):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.context = None
def post_setup(self, context):
self.context = context
def main():
with tempfile.TemporaryDirectory() as target_dir_path:
print(f" *** Created temporary directory '{target_dir_path}'.")
#
print(f" *** Creating virtual environment...")
venv_builder = EnvBuilder(with_pip=True)
venv_builder.create(str(target_dir_path))
venv_context = venv_builder.context
#
requirements = [
'requests',
]
print(f" *** Installing {requirements}...")
pip_install_command = [
venv_context.env_exe,
'-m',
'pip',
'install',
*requirements,
]
subprocess.check_call(pip_install_command)
#
print(" *** Generating script...")
script_substitutions = {
'venv_executable': venv_context.env_exe,
}
script = (
string.Template(SCRIPT_TEMPLATE).substitute(script_substitutions)
)
print(" *** Generated script:")
print("'''")
print(script)
print("'''")
#
script_path = pathlib.Path(target_dir_path).joinpath('run.py')
print(f" *** Writing script '{script_path}'")
script_path.write_text(script)
#
print(" *** Executing script...")
script_command = [
venv_context.env_exe,
str(script_path),
]
subprocess.check_call(script_command)
if __name__ == '__main__':
main()
添加回答
举报