PYTHON How to SET pythonpath in window 10 - python

I'm trying to set pythonpath but when I follow in some example in other stackoverflow, I just get a red message or nothing happened.
In my picture, u can see, no my folder D:\DemoPython
Does anyone have exactly how to set it?, please give me some examples or the exact answer would be better. Thank so much.

The syntax for setting environment variables you found is for cmd.exe (the DOS-like prompt that has shipped with Windows for ages). You're running in PowerShell, which is newer, and has significantly different syntax.
On PowerShell (which you're using), you want:
$env:PYTHONPATH = "D:\DemoPath;${env:PYTHONPATH}"
or
$env:PYTHONPATH = "${env:PYTHONPATH};D:\DemoPath"
depending on whether you want to take precedence over existing entries or not, respectively.

My Computer > Properties > Advanced System Settings > Environment Variables >
Just add the path as
C:\Users\zee\AppData\Local\Programs\Python\Python39 (or wherever you installed python)

Related

How do I add a directory to system environment variable using python script [duplicate]

From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?
The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.
My test code is
import os
os.environ['FAKE'] = 'C:\\'
Opening another instance of Python and requesting os.environ['FAKE'] yields a KeyError.
NOTE: Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.
That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.
You can using SETX at the command-line.
By default these actions go on the USER env vars.
To set and modify SYSTEM vars use the /M flag
import os
env_var = "BUILD_NUMBER"
env_val = "3.1.3.3.7"
os.system("SETX {0} {1} /M".format(env_var,env_val))
make them stick by committing them to
the system?
I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates.
If you really do think you need to set environment variables for the system you will need to look at changing them in the location they get initially loaded from like the registry on windows or your shell configuration file on Linux.
Under Windows it's possible for you to make changes to environment variables persistent via the registry with this recipe, though it seems like overkill.
To echo Brian's question, what are you trying to accomplish? There is probably an easier way.
Seems like there is simplier solution for Windows
import subprocess
subprocess.call(['setx', 'Hello', 'World!'], shell=True)
I don't believe you can do this; there are two work-arounds I can think of.
The os.putenv function sets the environment for processes you start with, i.e. os.system, popen, etc. Depending on what you're trying to do, perhaps you could have one master Python instance that sets the variable, and then spawns new instances.
You could run a shell script or batch file to set it for you, but that becomes much less portable. See this article:
http://code.activestate.com/recipes/159462/
Think about it this way.
You're not setting shell environment variables.
You're spawning a subshell with some given environment variable settings; this subshell runs your application with the modified environment.
According to this discussion, you cannot do it. What are you trying to accomplish?
You are forking a new process and cannot change the environment of the parent process as you cannot do if you start a new shell process from the shell
You might want to try Python Win32 Extensions, developed by Mark Hammond, which is included in the ActivePython (or can be installed separately). You can learn how to perform many Windows related tasks in Hammond's and Robinson's book.
Using PyWin32 to access windows COM objects, a Python program can use the Environment Property (a collection of environment variables) of the WScript.Shell object.
Try to use py-setenv that will allow you to set variable via registry
python -m pip install py-setenv
From within Python? No, it can't be done!
If you are not bound to Python, you should consider using shell scripts (sh, bash, etc). The "source" command allows you to run a script that modifies the environment and will "stick" like you want to the shell you "sourced" the script in. What's going on here is that the shell executes the script directly rather creating a sub-process to execute the script.
This will be quite portable - you can use cygwin on windows to do this.
In case someone might need this info. I realize this was asked 7 yrs ago, but even I forget how sometimes. .
Yes there is a way to make them "stick" in windows. Simply go control panel, system, advanced system settings,when the system properties window opens you should see an option (button) for Environment Variables. .The process for getting to this is a little different depending on what OS you're using (google it).
Choose that (click button), then the Environment Variables window will open. It has 2 split windows, the top one should be your "User Variables For yourusername". . .choose "new", then simply set the variable. For instance one of mine is "Database_Password = mypassword".
Then in your app you can access them like this: import os, os.environ.get('Database_Password'). You can do something like pass = os.environ.get('Database_Password').

'Invalid Python SDK' error right after creating a new project in PyCharm

Background
Some time ago I seriously crashed my Windows computer while using PyCharm - I remember some errors about memory and then a hard crash with no blue screen - just black with some thin vertical lines and reboot to Windows installation / fixing screen. Since then, I had this problem, with no way I found online to fix this.
Edit : Apparently, this has nothing to do with the problem.
The problem
Whenever I open a project, or create a new one, an error appears with the Invalid Python SDK error message.
**Invalid Python SDK**
Cannot set up a Python SDKat Python 3.9 (%projectName%) (%projectPath%).The SDK seems to be invalid.
Also, this is what the work environment looks like the moment I close this message. In the Project window, the venv directory (and every directory under it) is marked as an Exclusion, and in the code, the print(f'Hi, {name}') function is marked as an unresolved reference error shown below. The program, however, executes flawlessly.
What's more, when I go to Python Interpreter settings at File -> Settings -> Project -> Python Interpreter there's a yellow bar on the bottom which says:
Non-zero exit code (4).
which after some time says:
Python packaging tools not found.
Upon installing, nothing changes, and I can't add packages from this screen (the '+' button is greyed out):
When I try to check Python interpreter paths, there are no paths shown, and I don't know what that means:
In short, all of the default Python functions like print are marked as errors, even though they work when executed. This makes coding extremely confusing, as I can't quickly distinguish between real errors and 'errors'.
The search for solution
Normally this would be a problem with interpreter set-up or path, but I've tried most of the methods proposed in other answers to similar questions. To name a few :
PyCharm shows unresolved references error for valid code
'Cannot setup a Python SDK' in PyCharm project using virtualenv after OS reinstallation
Why do I get an 'SDK seems invalid' error when setting up my Project Interpreter in PyCharm?
Invalid Python SDK Error while using python 3.4 on PyCharm
Invalid Python SDK when setting a venv
There were supposed to be links, but I don't have enough reputation on Stack Overflow to post them with the questions. These, however, can be easily looked up in Google, all of them are posted to Stack Overflow.
What I tried
I should mention that the first things I tried were removing and installing PyCharm, all user configurations and Python itself as well. I installed Python from the official site, and from the PyCharm application, both methods ended with the same result.
File -> Invalidate Caches... -> Invalidate and restart. Didn't work.
Checking file interpreter in Edit Configurations. Don't know what to make of it. The result:
Refreshing the interpreter paths. Even now, the paths yield no results.
Removing the interpreter and adding it again. No result.
Deleting the .idea folder. No result.
Deleting PyCharm user preferences under %homepath%/.PyCharm50. I don't have that folder though.
Switching interpreter back and forth. No result.
Creating a new interpreter in a different location. No result.
Marking project directory as root ProjectName -> Mark Directory as -> Sources Root and unmarking other directories as Excluded. No result.
Using no interpreter. Yeah, it doesn't mark non-errors as errors anymore. But the code doesn't work. That's not a solution for me.
Checking if venv/pyvenv.cfg has paths set correctly. These look fine to me.
Checking Windows environment variables - Path variable. It was in the user section, but wasn't in the system section. I added it, restarted but still no result.
Changing account name in Windows. My account name was 'username' and that's how my User folder is called `C:\Users\username', but I later connected it to Microsoft account and my user name is now User Name with a space and I can't really change it. My folder stayed the same. Not sure if I can fix it that way.
To the two last things I tried I should also add that I changed my Windows username from 'username' to 'user name' with a space, but that wasn't until recently.
I'm attaching the idea.log file for you to check. I replaced my real username with 'User Name' to highlight the existence of a space.
OK, that was a lucky one! I'm thus posting my comment as an answer:
The problem is caused by the non-ASCII characters in the path, and the solution is to remove them. As indicated by #TheLazyScripter this is a known issue.

How to change the default python version/path in Rstudio

I am aware that similar questions have been asked before, but I either don't understand the answers, or there aren't any; so I decided to describe my problem in as much detail as possible.
Problem:
RStudio reticulate package uses Python from this path:
"/usr/bin/python"
but I want it to use python from this path - always, as a default:
"/Library/Frameworks/Python.framework/Versions/3.7/bin/python3"
How do I know it happens?
I open RStudio, and create a new python script. A new file with an extension .py is generated. I type something in:
import pandas as pd
and execute (by clicking cmd+enter). I then see what happens in the console - the reticulate package is called:
reticulate::repl_python()
Python 2.7.10 (/usr/bin/python)
Reticulate 1.12 REPL -- A Python interpreter in R.
I would like to permanently change where the reticulate package looks for Python.
From the Terminal I know:
$ python --version
Python 3.7.3
which python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
So, I would like to tell RStudio to always look in this path to find Python 3.7. I have tried to use the following command, run from an R script:
use_python("/Library/Frameworks/Python.framework/Versions/3.7/bin/python3")
but it doesn't do anything - my naive understanding is that this command is useful within an R markdown file, i.e. when I have code that combines R and Python, in separate chunks. I would like to change the path that is used when a Python script is run from within RStudio. Is there some kind of a config file I could edit?
I hope this makes sense. I am not a regular Python user, only started learning now, and I am also not very good with paths, so I would appreciate step-by-step answers.
OK, so I have posted too early - after some more googling I can solve this problem myself, but I think it is worth posting an answer here for people like me (i.e. not path-proficient or python-proficient).
There is something like a config file for R, called .Renviron. In order to access it, use Terminal to go to your home directory (i.e. the one that you go to when you type 'cd'). If you have never used this file before, it might not exist, in which case you need to create it.
Once in your home directory, type:
ls -a
then check on the list of files that appears whether .Renviron is there. Below are instructions what if you already have .Renviron (IF YES), and what if you don't (IF NO).
IF NO, type:
touch .Renviron
which creates the file.
IF YES, just proceed as below (without using the touch command).
Write:
nano .Renviron
the .Renviron file will open. In it, add a line that says:
RETICULATE_PYTHON="enter your desired path here"
so, in my case, this is:
RETICULATE_PYTHON="/Library/Frameworks/Python.framework/Versions/3.7/bin/python3"
now save the file by exiting nano (ctrl+x) and clicking 'y' when it asks whether to save changes (press 'y' then press enter).
restart you RStudio. It should work now. I hope this is useful!

GOPATH interpreted differently when calling directly versus Python subprocess

I recently found a fix for Python getpass not working on Windows: Python not working in the command line of git bash
Or at least that was the last thing I remember about changing my python configurations. (This is for Python 3.6.1 on Windows 10)
Now I also use Python to other tasks which simply has subprocess calls to type several commands on terminal:
go build ./folder/
mv ./src/ ./bin/
I get the error: go: GOPATH entry is relative; must be absolute: "/c/Users/OP/work". But I don't get it if I type go build ./src/folder myself.
I have GOPATH set to C:\work in Environment Variables. I have tried with a ;.
Is there a way to reverse the alias python every time? Or what is happening exactly when setting an alias for python to winpty?
I'm thinking that when I call go build directly, it is called by either my user profile or system. And when python's subprocess calls it, it calls the opposite. Therefore, I have two GOPATH variables even though I have only 1 set in environment variable.
Side Note: another recent change on GOPATH was changing it from C:/go because it couldn't be the same as GOROOT. That error popped up randomly for some reason. It worked with that setting for a while and I don't remember changing anything before except adding another import package on top of the many other ones already being used.
Update: with type python I get the result: python is aliased to 'winpty python.exe'. Therefore I tried to undo that with unalias python. The new result I get is: python is hashed (/c/Users/OP/AppData/Local/Programs/Python/Python36/python).
This fixed the go build command within Python's subprocess. However, that alias was a fix for another Python issue with using getpass package.
On top of my unalias python fix, I also discovered something interesting: when I change the environment variables for GOPATH from C:\work; to C:\go, all go commands still spit the error go: GOPATH entry is relative; must be absolute: "". I got this same error (but different path) from updating Windows 10 Fall Creators update. Maybe it is related.
Simply closing MINGW and reopening it fixed the issue. So perhaps it was saying a copy of my environment variables and using that as a reference instead of the actual system properties.
I know this is not a popular question, but someone could benefit from my hours of investigating and debugging.
Under Windows you must use a Windows style GOPATH like eg d:\code and probably you should use cmd shell and nothing else. Unfortunately cygwin paths (and probably others too) do no longer work especially for go get reaching out to git.
Stick to Windows paths and Windows shell.

Find out windows shortcut path

In windows, I can make a number of shortcuts. I want to know whether the program is opened as shortcut, or itself. And finally I hope to know where the shortcuts path location is in my program. Unfortunately, I use python so I hope a solution in python.
__file__ will get you the name of the invoked script. If it is a link, it should change accordingly.
You can check if the file is a link via the following:
import os
islink = os.path.islink(__file__)
islink will contain a boolean value with the answer.
I tested this out on Ubuntu, but this should in theory work on Windows, also, via POSIX.
More info:
https://docs.python.org/2/library/os.path.html#os.path.islink
I'm not quite sure what you mean by this question:
And finally I hope to know where the shortcuts path location is in my
program.

Categories

Resources