I would like to import some functions I regularly use into my scripts, instead of having to paste them in it.
This is the reading I get when I check with the path browser:
>>> sys.path
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\Lib\idlelib
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\python37.zip
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\DLLs
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\lib
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\lib\sitepackages
I'd like to permanently add the following path to it:
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\PythonScripts
I've tried the following:
path = 'C:/Users/Apex/AppData/Local/Programs/Python/Python37-32/PythonScripts'
import sys, os
sys.path.append(path)
All the paths above and the one I want to add appear in the shell, but when I check the path browser, mine isn't there.
How can I set PythonScripts to Python's path permanently?
I read up a bit on PYTHONPATH, but I didn't understand how to use it.
Please, when you reply, don't I assume I might know everything you do. Thanks.
I'm using window 7 with Python v3.7.0
Just in case that this might help someone else, this is what worked for me:
I moved the PythonScripts folder out of the Python37-32 and into the Apex folder, and I added the path to it and to another folder to the Windows Environment Viariables like this:
Variable name: PYTHONPATH
Variable value: C:\Users\Apex\PythonScripts;C:\xampp\htdocs\PythonScripts
The suggestion given in the posting I was pointed to of using:
C:\Python27
did not work for me.
Thanks to all for their valuable input.
Related
I would like to change the defaut working directory in python on windows. I mean the default path is c:/users/usename and every time you start python you need to do
import os
os.chdir(path)
to modify it.
I would like to know if there is a way to set new directory by defaut?
For exemple with R we can do that by editing Rprofile file. But for python I don't know (i don't find) if there is this type of file.
Thank you in advance
Stéphane
You can use pathlib.
Python uses environment variables of your os. Therefore you have to adjusted your %PATH% to get what you would like to do.
import pathlib
current_dir = pathlib.Path()
print(current_dir.pwd)
output: the directory where you started your script
Well, there is no way of permanently changing the default working directory in Python that I am aware of.
But, there are some things you can do like:
If you are launching Python from the start menu of Windows, right-click on the icon and select more > file location.
Once there you can right-click on the shortcut and select properties. From there you should be able to define the Start In location.
This could be one way to change your default directory.
Hope this answer helps you.
Coming from R, using setwd to change the directory is a big no-no against reproducibility because others do not have the same directory structure as mine. Hence, it's recommended to use relative path from the location of the script.
IDEs slightly complicate this because they set their own working directory. In Rstudio, I can easily get around this problem with Rstudio's projects, setting the project's directory to be my script folder.
With Python and Spyder, there doesn't seem to be any solution. Spyder does not have a feature like Rstudio's project. Setting the directory to the script's location does not work while doing interactive analysis (since __file__ is not available).
What to do so that the working directory in Python / Spyder is reproducible?
To do this automatically, put this at the beginning of your script:
from os import chdir, getcwd
wd=getcwd()
chdir(wd)
In the interim, you can use os.chdir
import os
os.chdir('C:\Users\me\Documents')
It appears they did consider this as a feature in Spyder based on this GitHub ticket, but it is still waiting implementation as of mid-May:
We could add an option to the Run dialog to automatically set the
working directory to the one your script is being ran.
However, someone else will have to implement it. We're pretty busy
with other things at the moment, sorry.
https://github.com/spyder-ide/spyder/issues/3154
#ccordoba12 ccordoba12 added this to the wishlist milestone on May 14
as I wrote here, Mark8888 pointed out to run the whole script (run file (F5)) instead of just pieces of the script
this way multiple approaches should work to get the script file location and change the current working directory
import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())
also
import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())
Well, there are a lot of things that you can try!
1. Change the directory to the current directory in the toolbar.
2. Change the Global directory to the current directory in Preferences>Global Working Directory. Click 'the current file directory' radio button.
Hope it helps!
I tried this and it works.
import os
abspath = os.path.abspath('') ## String which contains absolute path to the script file
os.chdir(abspath) ## Setting up working directory
I have been trying to fix the python path on my cpu, and I originally was just trying to change my .bash_profile, but that wasn't working, so I used
import sys
sys.pat.append(path/To/Module)
and now when I run my script, I get this error message
How can I either fix this issue or undo the sys.path.append(path/To/Module)?
Also, is it possible to export multiple directories in the python path, and if so how do I do that?
Note that if you add a path with sys.path.append() you do this only for the current session. No need to undo it.
Just remove the line from you python file.
Have you tried sys.path.pop()
That will remove the last item that you added or indeed the last item on the PYTHONPATH, whatever that might be.
How can I either fix this issue or undo the >sys.path.append(path/To/Module)?
To undo the sys.path.append, you just need to remove that line from your script. Since the path is only modified for your current script and not system wide until you edit the PYTHONPATH.
Also, is it possible to export multiple directories in the python path, and if so how do I do that?
If you want to do it using sys, you can do it like:
sys.path.extend(['/path1', '/path2'])
recently I found that pycharm ide will automatically append certain directory to your sys.path if you marked that directory as Sources Root. So even if you use sys.path.pop(sys.path.index(**directory path**), it wouldn't work. Just unmark the folder and the issue will be solved.
I have spent a few hours trying to solve this problem but didn't manage yet. I figure my question is a bit specific to my own mac configuration and I need a more detailed instruction.
So my problem is that I installed Ruby using home-brew, for some reason, this installation changed my default python site-package directory. Before I have Ruby, my terminal python will automatically call the site-package from the path '/Users/xxxxxx/canopy/lib/python2.7/site-packages'. However, it now will use '/Library/Python/2.7/site-packages'. I tried three different ways to solve this issue but all failed:
1 use Canopy Terminal like this Set Canopy Preference, but this method point to another directory '/Applications/Canopy.app/appdata/canopy-1.5.2.2785.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages', which is not i want either.
2 change the bash_profile like this amend path, but by just putting the # in every line of the bash_profile, it still use directory '/Library/Python/2.7/site-packages'. Btw, my bash_profile and $PATH looks like this before:
and looks like this
3 add the path '/Users/xxxxxx/canopy/lib/python2.7/site-packages' into sys.path, which look like this now:
But none of those worked. How can I make my terminal point to the path '/Users/xxxxxx/canopy/lib/python2.7/site-packages' now? Or ultimately, what should I do to clean up those different site-packages and use the one I only need?
Thank you for any help!
On a mac by default the path is /Library/Python/2.7/site-packages/foo.egg.
Before doing anything, in terminal, start a new Python session and do
import sys
print sys.path
If the paths are of the form /Library/Python/2.7/site-packages/foo.egg, then just follow link
tl;dr
Basically add this to your bash_profile,
source [...] /activate
VIRTUAL_ENV_DISABLE_PROMPT=1 source [...] activate
I found the solution:
added to the bash_profile this line " export PATH="$HOME/canopy/bin:$PATH" ", and uncomment all other lines in bash_profile.
Currently, when trying to reference some library code, I'm doing this at the top of my python file:
import sys
sys.path.append('''C:\code\my-library''')
from my-library import my-library
Then, my-library will be part of sys.path for as long as the session is active. If I start a new file, I have to remember to include sys.path.append again.
I feel like there must be a much better way of doing this. How can I make my-library available to every python script on my windows machine without having to use sys.path.append each time?
Simply add this path to your PYTHONPATH environment variable. To do this, go to Control Panel / System / Advanced / Environment variable, and in the "User variables" sections, check if you already have PYTHONPATH. If yes, select it and click "Edit", if not, click "New" to add it.
Paths in PYTHONPATH should be separated with ";".
You should use
os.path.join
to make your code more reliable.
You have already used __my-library__ in the path. So don't use it the second time in import.
If you have a directory structure like this
C:\code\my-library\lib.py and a function in there, e.g.:
def main():
print("Hello, world")
then your resulting code should be
import sys
sys.path.append(os.path.join('C:/', 'code', 'my-library'))
from lib import main
If this is a library that you use throughout your code, you should install it as such. Package it up properly, and either install it in your site-packages directory - or, if it's specific to certain projects, use virtualenv and install it just within the relevant virtualenvs.
To do such a thing, you'll have to use a sitecustomize.py (or usercustomize.py) file where you'll do your sys.path modifications (source python docs).
Create the sitecustomize.py file into the \Lib\site-packages directory of your python installation, and it will be imported each time a python interpreter is launched.
If you are doing this interactively, the best thing to do would be to install ipython and configure your startup settings to include that code. If you intend to have it be part of a script you run from the interpreter, the same thing applies, since it will have access to your namespace.
On the other hand, a stand alone script should not include that automatically. In the future, you or some other maintainer will come along, and all the code should be obvious, and not dependent upon a specific machine setup. The best thing to do would be to set up a skeleton file for new projects that includes all of the basic functionality you need. That, along with oft-used snippets will handle the problem.
All of your code to run the script, will be in the script, and you won't have to think about adding that code every time.
Using jupyter with multiple environments, adding the path to .bashrc didn't work. I had to edit the kernel.json file for that particular kernel and append it to the PYTHONPATH in env section.
This only worked in that kernel but maybe this can help someone else.