Skip to content

Commit 26c75ff

Browse files
authored
Update Run_WSL_Python_Script_in_VEnv.py
1 parent 7c9001e commit 26c75ff

File tree

1 file changed

+96
-59
lines changed

1 file changed

+96
-59
lines changed

Run_WSL_Python_Script_in_VEnv.py

+96-59
Original file line numberDiff line numberDiff line change
@@ -4,74 +4,111 @@
44
import os
55
import subprocess
66
import sys
7+
import tempfile
78

89
def is_wsl():
9-
try:
10-
with open("/proc/version", "r") as f:
11-
return "microsoft" in f.read().lower()
12-
except FileNotFoundError:
13-
return False
10+
    try:
11+
        with open("/proc/version", "r") as f:
12+
            return "microsoft" in f.read().lower()
13+
    except FileNotFoundError:
14+
        return False
1415

15-
def find_activate():
16-
cwd = os.getcwd()
17-
for root, dirs, files in os.walk(cwd):
18-
if 'bin' in dirs:
19-
activate_path = os.path.join(root, 'bin', 'activate')
20-
if os.path.isfile(activate_path):
21-
return activate_path
22-
return None
16+
def find_all_venvs():
17+
    # Search for virtual environments in the user's WSL home directory
18+
    home_dir = os.path.expanduser("~")
19+
    venvs = []
20+
    for root, dirs, files in os.walk(home_dir):
21+
        if 'bin' in dirs:
22+
            activate_path = os.path.join(root, 'bin', 'activate')
23+
            if os.path.isfile(activate_path):
24+
                venvs.append(root)
25+
    return venvs
2326

2427
def ensure_virtualenv():
25-
if sys.prefix != sys.base_prefix:
26-
return
27-
activate_path = find_activate()
28-
if activate_path:
29-
print(f"Found activation script at: {activate_path}")
30-
venv_python = os.path.join(os.path.dirname(activate_path), "python")
31-
if not os.path.exists(venv_python):
32-
print("Python interpreter not found in the virtual environment.")
33-
input("Press Enter to exit...")
34-
sys.exit(1)
35-
print("Re-launching the script with the virtual environment's interpreter...")
36-
subprocess.run([venv_python] + sys.argv)
37-
input("Press Enter to exit...")
38-
sys.exit(0)
39-
else:
40-
print("No virtual environment activation script found in the current directory or its subdirectories.")
41-
input("Press Enter to exit...")
42-
sys.exit(1)
28+
    # If already in a virtual environment, continue
29+
    if sys.prefix != sys.base_prefix:
30+
        return
31+
32+
    venvs = find_all_venvs()
33+
    if not venvs:
34+
        print("No virtual environments found in your home directory.")
35+
        input("Press Enter to exit...")
36+
        sys.exit(1)
37+
38+
    print("Virtual environments found in your home directory:")
39+
    for i, venv in enumerate(venvs, start=1):
40+
        print(f"{i}. {venv}")
41+
42+
    try:
43+
        choice = int(input("Select the number of the virtual environment you want to activate: "))
44+
        if choice < 1 or choice > len(venvs):
45+
            print("Invalid selection.")
46+
            sys.exit(1)
47+
    except ValueError:
48+
        print("Please enter a valid number.")
49+
        sys.exit(1)
50+
51+
    selected_venv = venvs[choice - 1]
52+
    venv_python = os.path.join(selected_venv, "bin", "python")
53+
    if not os.path.exists(venv_python):
54+
        print("Python interpreter not found in the selected virtual environment.")
55+
        input("Press Enter to exit...")
56+
        sys.exit(1)
57+
58+
    print("Re-launching the script with the virtual environment's interpreter...")
59+
    # Replace the current process with the selected venv's Python interpreter
60+
    os.execv(venv_python, [venv_python] + sys.argv)
4361

4462
def select_and_run_py():
45-
py_files = [f for f in os.listdir('.') if f.endswith('.py') and os.path.isfile(f)]
46-
if not py_files:
47-
print("No Python files found in the current directory.")
48-
return
63+
    # List Python files in the current working directory
64+
    py_files = [f for f in os.listdir('.') if f.endswith('.py') and os.path.isfile(f)]
65+
    if not py_files:
66+
        print("No Python files found in the current directory.")
67+
        return
68+
69+
    print("Python files in the current directory:")
70+
    for i, filename in enumerate(py_files, start=1):
71+
        print(f"{i}. {filename}")
4972

50-
print("Python files in the current directory:")
51-
for i, filename in enumerate(py_files, start=1):
52-
print(f"{i}. {filename}")
73+
    try:
74+
        choice = int(input("Select the number of the .py file you want to run: "))
75+
        if choice < 1 or choice > len(py_files):
76+
            print("Invalid selection.")
77+
            return
78+
    except ValueError:
79+
        print("Please enter a valid number.")
80+
        return
5381

54-
try:
55-
choice = int(input("Select the number of the .py file you want to run: "))
56-
if choice < 1 or choice > len(py_files):
57-
print("Invalid selection.")
58-
return
59-
except ValueError:
60-
print("Please enter a valid number.")
61-
return
82+
    selected_file = py_files[choice - 1]
83+
    command = [sys.executable, selected_file]
84+
   
85+
    print(f"Executing command: {' '.join(command)}")
86+
    subprocess.run(command)
6287

63-
selected_file = py_files[choice - 1]
64-
command = [sys.executable, selected_file]
65-
66-
print(f"Executing command: {' '.join(command)}")
67-
subprocess.run(command)
88+
def drop_to_shell(venv_path):
89+
    # Prepare a temporary rcfile that sources the venv activation script,
90+
    # echoes a message, and sets the prompt to display the venv name.
91+
    activate_script = os.path.join(venv_path, "bin", "activate")
92+
    venv_name = os.path.basename(venv_path)
93+
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp:
94+
        tmp.write(f'source "{activate_script}"\n')
95+
        tmp.write('echo "The virtual environment is activated!"\n')
96+
        # Manually set the prompt to include the virtual environment name
97+
        tmp.write(f'export PS1="({venv_name}) \\u@\\h:\\w\\$ "\n')
98+
        tmp_path = tmp.name
99+
    print("\nDropping to an interactive shell. Type 'exit' to close the shell.")
100+
    os.system(f"bash --rcfile {tmp_path} -i")
101+
    os.remove(tmp_path)
68102

69103
if __name__ == "__main__":
70-
if not is_wsl():
71-
print("This script must be run inside WSL2. Exiting...")
72-
input("Press Enter to exit...")
73-
sys.exit(1)
74-
75-
ensure_virtualenv()
76-
77-
select_and_run_py()
104+
    if not is_wsl():
105+
        print("This script must be run inside WSL2. Exiting...")
106+
        input("Press Enter to exit...")
107+
        sys.exit(1)
108+
   
109+
    ensure_virtualenv()
110+
    select_and_run_py()
111+
   
112+
    # After running the selected .py file, drop to an interactive shell
113+
    if sys.prefix != sys.base_prefix:
114+
        drop_to_shell(sys.prefix)

0 commit comments

Comments
 (0)