Issue
I have a Python script that creates a virtual environment in the following way:
import os
import subprocess
virtualenv_path = os.path.join("/tmp", "my-environment")
subprocess.run(["virtualenv", virtualenv_path], check=True)
This works just fine. However in the Virtualenv documentation I saw that you can "trigger invocation of Python environments from within Python". To do this "you should be using the virtualenv.cli_run method; this takes an args argument where you can pass the options the same way you would from the command line. The run will return a session object containing data about the created virtual environment."
So I ran the following instead:
from virtualenv import cli_run
cli_run(["virtualenv", "/tmp/my-environment"])
However this gives me the following error:
usage: virtualenv [--version] [--with-traceback] [-v | -q] [--read-only-app-data] [--app-data APP_DATA] [--reset-app-data] [--upgrade-embed-wheels] [--discovery {builtin}] [-p py] [--try-first-with py_exe]
[--creator {builtin,cpython3-posix,venv}] [--seeder {app-data,pip}] [--no-seed] [--activators comma_sep_list] [--clear] [--no-vcs-ignore] [--system-site-packages] [--symlinks | --copies] [--no-download | --download]
[--extra-search-dir d [d ...]] [--pip version] [--setuptools version] [--wheel version] [--no-pip] [--no-setuptools] [--no-wheel] [--no-periodic-update] [--symlink-app-data] [--prompt prompt] [-h]
dest
virtualenv: error: unrecognized arguments: /tmp/my-environment
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
I am really unsure about why this doesn't work as I am passing the same arguments as I would on the command line.
Solution
When you call cli_run
as part of virtualenv, you don't need to include the program name, in this case "virtualenv". Simply include your destination, along with any other arguments.
Answered By - user3832673 Answer Checked By - David Goodson (WPSolving Volunteer)