I am working in Windows 11, Python 3.10, Mu 1.1.0. I followed the instructions on ATBS to create a batch file to run a script from the WIN + R launcher. However in CMD the error A(below) pops up. I tried following instructions from the documentation on python.org, and in Appendix B of ATBS to edit environment variables. I added the following to PATH env variables: C:\Users\19139\MyPythonScript; C:\Users\19139\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\Python 3.10 (64-bit).lnk; and C:\Users\19139\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.10\Python 3.10 (64-bit).lnk\Scripts. Is there some issue with the fact that the PATH includes start menu? All I am able to call from CMD is py --version. When I try and directly call a python script I get Error B. I disabled the "App Installer"(s) under App Aliases for Python.exe and Python3.exe but no change in error. I can call py --version, but I am beyond the scope of my ability to figure out what to do. I am unsure of next possible step to problem solve, suggestions welcome.
Error A:
`enter code here`Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'C:\Users\19139\AppData\Local\Programs\Python\Python310\python.exe'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\python.exe'
sys.base_prefix = ''
sys.base_exec_prefix = ''
sys.platlibdir = 'lib'
sys.executable = 'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\python.exe'
sys.prefix = ''
sys.exec_prefix = ''
sys.path = [
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\Lib\\',
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310\\DLLs\\',
'C:\\Users\\19139\\AppData\\Local\\Programs\\Python\\Python310',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
Traceback (most recent call last):
File "C:\Users\19139\AppData\Local\Programs\Python\Python310\Lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'
Error B
C:\Users\19139>python "C:\Users\19139\MyPythonScript\mClip.py"
Python was not found; run without arguments to install from the Microsoft Store, or
disable this shortcut from Settings > Manage App Execution Aliases.
First of all, unlike ubuntu/ linux Windows doesn't detect python on its own. That's why we need to specify the path manually, to make it aware of python.
Is there some issue with the fact that the PATH includes start menu?
Yes, there is issue there. PATH for python doesn't include Start Menu generally.
You are looking at the wrong place or have installed python package at the wrong location. Find the correct python package location.
Python PATH looks something like this:
C:\Users\user_name\python_installerpkg_name
For example, if you have installed python using a python installer pkg like anaconda/ mini-conda, you can use its command prompt to find the location via where python. Then use the location to set the PATH in environment variables. the PATH would look like: C:\Users\user_name\anaconda
Error B
Until you configure the correct path in the environment variables you won't be able to use the command python filename.py from the command line.
On Windows 10, I'm running VS Code 1.48.2 and Python 3, both installed on a thumb drive. I added an F:\Programs\VS Code\data folder with user-data andextensions. My project directory is F:\MyProject and it has a Pipfile. My project directory has a .env file and .venv\ so that pipenv will install to the local .venv\. What else do I need to get this environment working? Thanks!
.env file:
PYTHONPATH="F:\\Python\\Python38\\python.exe"
PYTHONHOME="F:\\MyProject\\.venv\\Scripts"
PIPENV_VENV_IN_PROJECT=True
F:\MyProject\.vscode\settings.json file:
{
"python.pythonPath": "f:\\MyProject\\.venv\\Scripts\\python.exe"
}
Although, when I used Preferences: Open Settings, it opened my F:\Programs\VS Code\data\user-data\settings.json file, though the paths look right (to me):
{
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"python.languageServer": "Microsoft",
"python.pythonPath": "${workspacefolder}/.venv/Scripts/python.exe",
"python.venvPath": "${workspacefolder}/.venv",
"python.venvFolders": [
".venv",
"${workspacefolder}/.venv"
]
}
Used the following steps to setup:
ps > cd F:\MyProject
ps > F:\Programs\VS Code\code.exe .
[In vscode integrated terminal]
PS F:\MyProject> py -m venv --system-site-packages .venv
PS F:\MyProject> pipenv shell
Loading .env environment variables…
Warning: Your Pipfile requires python_version 3.8, but you are using unknown (F:\M\.venv\S\python.exe).
$ pipenv --rm and rebuilding the virtual environment may resolve the issue.
$ pipenv check will surely fail.
Launching subshell in virtual environment…
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS F:\MyProject> ls .\.venv\Scripts\python.exe
Directory: F:\MyProject\.venv\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 9/6/20 3:04 PM 532040 python.exe
PS F:\MyProject> python where
Python path configuration:
PYTHONHOME = 'F:\MyProject\.venv\Scripts'
PYTHONPATH = 'F:\Python\Python38\python.exe'
program name = 'F:\Python\Python38\python.exe'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'F:\\Python\\Python38\\python.exe'
sys.base_prefix = 'F:\\MyProject\\.venv\\Scripts'
sys.base_exec_prefix = 'F:\\MyProject\\.venv\\Scripts'
sys.executable = 'F:\\MyProject\\.venv\\Scripts\\python.exe'
sys.prefix = 'F:\\MyProject\\.venv\\Scripts'
sys.exec_prefix = 'F:\\MyProject\\.venv\\Scripts'
sys.path = [
'F:\\Python\\Python38\\python.exe',
'F:\\Python\\Python38\\python38.zip',
'F:\\MyProject\\.venv\\Scripts\\DLLs',
'F:\\MyProject\\.venv\\Scripts\\lib',
'F:\\Python\\Python38',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
Current thread 0x000020d4 (most recent call first):
<no Python frame>
PS F:\MyProject>
According to your description, you could refer to the following steps to use the virtual environment:
Open this project in VSCode.
According to the information you provided, there is already a virtual environment ".venv" in your project, so there will be a ".venv" folder after opening. like this:
Click "select Python Interpreter" in the lower left corner to select the ".venv" virtual environment:
VSCode has selected the virtual environment, and then we open a new terminal console through the shortcut key "Ctrl+Shift+`", VSCode will automatically enter the current virtual environment:
Use pip to install the module "PySimpleGui": (pip install PySimpleGui)
When we run the python script, VSCode showed that the module PySimpleGui could not be found. We found "Lib\site-packages" in the ".venv" folder of the project and changed "PySimpleGUI" to "PySimpleGui":
The python script runs successfully in the virtual environment:
I need to run some functions after activating the virtual environment.
I want to activate the virtual env from the same script which is containing the functions.
I am using the following code :
if 'VUNET_VIRT_ENV' in os.environ:
VUNET_VIRT_ENV = os.environ['VUNET_VIRT_ENV']
else:
VUNET_VIRT_ENV = '/home/ubuntu/workspace/vunetenv/'
VIRTENV_ACTIVATE_FILE = VUNET_VIRT_ENV + 'bin/activate_this.py'
exec(compile(open(VIRTENV_ACTIVATE_FILE).read(),
VIRTENV_ACTIVATE_FILE,
'exec'))
I am getting the following error while running the script:
Command '' returned non-zero exit status 1
there is activate_this.py in the defined location. But I can't figure out what went wrong? I am running in Linux.
Note: I'm on Windows using Git Bash.
So, I am trying to setup a dev environment for the work for my class. It is going to involve a combination of coding in R and Python.
I created virtual environments using pipenv and virtualenv and ran into the same problem with both. So, first, let's create a virtual environment for the project in a sub-folder dev_env:
cd project_folder/dev_env
pipenv --python 3.7
pipenv --py
Output
C:\Users\Ra Me\.virtualenvs\dev_env-5TUtSZI9\Scripts\python.exe
Now I'm going into my file.rmd and trying the reticulate package.
#install.packages("reticulate")
library(reticulate)
Next, I tried 2 methods:
Sys.setenv(RETICULATE_PYTHON = "C:/Users/Ra Me/.virtualenvs/dev_env-5TUtSZI9/Scripts")
or
use_virtualenv("C:/Users/Ra Me/.virtualenvs/dev_env-5TUtSZI9/", required = TRUE)
x = 1
if x:
print('Hello!')
Both of them produced the error
Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'
However, when I change the path to the Python environment that's installed for all users on my machine, it works.
Sys.setenv(RETICULATE_PYTHON = "C:/Program Files/Python37/")
This method also works. However, here we are not even using the reticulate project.
knitr::opts_chunk$set(engine.path = list(
python = "C:/Program Files/Python37/python.exe",
r = "C:/Program Files/R/R-3.6.1/bin/R.exe"
))
I want to activate a virtualenv instance from a Python script.
I know it's quite easy to do, but all the examples I've seen use it to run commands within the env and then close the subprocess.
I simply want to activate the virtualenv and return to the shell, the same way that bin/activate does.
Something like this:
$me: my-script.py -d env-name
$(env-name)me:
Is this possible?
Relevant:
virtualenv › Invoking an env from a script
If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:
import subprocess
# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"
# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"
subprocess.Popen([python_bin, script_file])
However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:
# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
execfile(activate_this_file, dict(__file__=activate_this_file))
The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:
#!/path/to/project/venv/bin/python
Make the script executable:
chmod u+x script.py
Run the script:
./script.py
Voila!
It turns out that, yes, the problem is not simple, but the solution is.
First I had to create a shell script to wrap the "source" command. That said I used the "." instead, because I've read that it's better to use it than source for Bash scripts.
#!/bin/bash
. /path/to/env/bin/activate
Then from my Python script I can simply do this:
import os
os.system('/bin/bash --rcfile /path/to/myscript.sh')
The whole trick lies within the --rcfile argument.
When the Python interpreter exits it leaves the current shell in the activated environment.
Win!
To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):
/path/to/virtualenv/bin/python
The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:
me$ /path/to/virtualenv/bin/python myscript.py
The same for a Windows environment (whether it is from the command line or from a script):
> \path\to\env\Scripts\python.exe myscript.py
Just a simple solution that works for me. I don't know why you need the Bash script which basically does a useless step (am I wrong ?)
import os
os.system('/bin/bash --rcfile flask/bin/activate')
Which basically does what you need:
[hellsing#silence Foundation]$ python2.7 pythonvenv.py
(flask)[hellsing#silence Foundation]$
Then instead of deactivating the virtual environment, just Ctrl + D or exit. Is that a possible solution or isn't that what you wanted?
The top answer only works for Python 2.x
For Python 3.x, use this:
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))
Reference: What is an alternative to execfile in Python 3?
The child process environment is lost in the moment it ceases to exist, and moving the environment content from there to the parent is somewhat tricky.
You probably need to spawn a shell script (you can generate one dynamically to /tmp) which will output the virtualenv environment variables to a file, which you then read in the parent Python process and put in os.environ.
Or you simply parse the activate script in using for the line in open("bin/activate"), manually extract stuff, and put in os.environ. It is tricky, but not impossible.
For python2/3, Using below code snippet we can activate virtual env.
activate_this = "/home/<--path-->/<--virtual env name -->/bin/activate_this.py" #for ubuntu
activate_this = "D:\<-- path -->\<--virtual env name -->\Scripts\\activate_this.py" #for windows
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
I had the same issue and there was no activate_this.py in the Scripts directory of my environment.
activate_this.py
"""By using execfile(this_file, dict(__file__=this_file)) you will
activate this virtualenv environment.
This can be used when you must use an existing Python interpreter, not
the virtualenv bin/python
"""
try:
__file__
except NameError:
raise AssertionError(
"You must run this like execfile('path/to/active_this.py', dict(__file__='path/to/activate_this.py'))")
import sys
import os
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if(sys.platform=='win32'):
site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = base
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
Copy the file to the Scripts directory of your environment and use it like this:
def activate_virtual_environment(environment_root):
"""Configures the virtual environment starting at ``environment_root``."""
activate_script = os.path.join(
environment_root, 'Scripts', 'activate_this.py')
execfile(activate_script, {'__file__': activate_script})
activate_virtual_environment('path/to/your/venv')
Refrence: https://github.com/dcreager/virtualenv/blob/master/virtualenv_support/activate_this.py
You should create all your virtualenvs in one folder, such as virt.
Assuming your virtualenv folder name is virt, if not change it
cd
mkdir custom
Copy the below lines...
#!/usr/bin/env bash
ENV_PATH="$HOME/virt/$1/bin/activate"
bash --rcfile $ENV_PATH -i
Create a shell script file and paste the above lines...
touch custom/vhelper
nano custom/vhelper
Grant executable permission to your file:
sudo chmod +x custom/vhelper
Now export that custom folder path so that you can find it on the command-line by clicking tab...
export PATH=$PATH:"$HOME/custom"
Now you can use it from anywhere by just typing the below command...
vhelper YOUR_VIRTUAL_ENV_FOLDER_NAME
Suppose it is abc then...
vhelper abc