python change starting up/default directory - python

I am new to python.
Every time I start the shell, it always gives me directory as:
".../file name/Python/"
But I want to change it to:
".../file name/python program/"
How do I do it without changing the import modulate stuff?
I am afraid to make it wrong so that I can't import anymore, but it is so annoy to put:
import os
os.chdir(".../file name/python program/")
every time after I open the shell.
Thanks for help!

Checkout: http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP
This is an environment variable that can be set to a file. This is executed prior to start up of shell and only applies if you are using interactive shell.
You can use this to specify a path as current directory at start of your shell.
import os
os.chdir('/pathto')
del os
Write to a file and point to it with env variable.
If this is just specific to a file that you are running, then you should be changing the directory inside the script
os.chdir('/pathto')

If you are trying to set up python so that it will automatically search in a specific directory on your computer when you import modules, open to your /python27/Lib/site.py file and add your paths to the PREFIXES list near the top of the file

Related

vscode get path of current file from inside python script

When ran from a terminal, sys.argv[0] is the path of current script, but in python interactive that variable points to "/some/path/ipykernel_launcher.py" which is a temporary file.
How do I get the path of current script (which I am editing in vscode)? I need this information because whenever I create a file, I automatically log which script created it. For that, I overload the open() function to automatically log the creation. But when file is created from a python interactive session, I am missing such information.
import os
print(os.getcwd())
I think that's what you want. It prints the current working directory.
The answer that works for me, obtained from How do I get the path and name of the file that is currently executing? is this:
os.path.realpath(__file__)
I tried all other suggestions, but didn't work.

Forced to enter full pathname every time instead of just file name

Every time I try to do an action such as running a program in the VScode Terminal (also happens in PyCharm) I have to enter in the full pathname instead of just the file name. For example, instead of just doing python3 test.py to run a program, I have to enter in python3 /Users/syedrishad/Desktop/Code/test.py.
Now, this is annoying and all but it doesn't bother me too much. What does bother me is when my program is trying to pull/ open files from somewhere else. If I wanted an image call Apple.jpeg, instead of just typing in Apple.jpeg, I'd have to go and find the full pathname for it. If I were to upload a piece of code doing this to someplace like GitHub, the person who'd want to test this code out for themselves will have to go in and replace each pathname with just the file name or it won't work on their computer. This problem has been going on for a while, and I sadly haven't found a solution to this. I would appreciate any help I get. I'm also on a Mac if that makes a difference.
You could use os and sys that gives you the full path to the folder of the python file.
Sys gives you the path and os gives you the possibility to merge it with the file name.
import sys, os
print(sys.path[0]) # that is the path to the directory of the python file
print(sys.path[0]+'/name.txt') #full path to the file
print(os.path.join(sys.path[0],'name.txt')) # os.path.join takes two parameters and merges them as one path using / but the line above is also fine
In VS Code, its internal terminal is in the currently opened project folder by default. Therefore, when you use the command "python file_name.py" to run the file, the terminal cannot find the file that exists in the inner folder.
Therefore, in addition to using the file path, we can also add related settings to help it find the file.
Run: When using the run button to execute the file, we can add the following settings in "settings.json", it will automatically enter the parent folder of the executed file.
"python.terminal.executeInFileDir": true,
"When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder."
debug: For debugging code, we need to add the following settings in "launch.json":
"cwd": "${fileDirname}",

Is it possible to access the launching shortcut directory from a Python executalbe?

I currently have a Python scrip that runs through all Excel files in the current directory and generates a PDF report.
It works fine now but I don't want the users to be anywhere near frozen Python scripts. I created an MSI with cxFreeze which puts the EXE and scripts in the Program Files directory.
What I would like to be able to do is create a shortcut to this executable and pass the directory the shortcut was run from to the Python program so that can be set as the working directory. This would allow the user to move the shortcut to any folder of Excel files and generate a report there.
Does Windows send the location of a opened shortcut to the executable and is there a way to access it from Python?
When you launch a shortcut, Windows changes the working directory to the directory specified in the shortcut, in the Start in field. At this point, Windows has no memory of where the shortcut was stored.
You could change the Start in field to point to the directory that the shortcut is in. But you'd have to do that for every single shortcut, and never make a mistake.
The better approach is to use a script, rather than a shortcut. Place your actual Python script (which we'll call doit.py for sake of example) somewhere in your PYTHONPATH. Then create a single-line Python script that imports it:
import doit
Save it (but don't name it doit.py) and copy it to each directory from which you want to be able to invoke the main script. In doit.py you can use os.getcwd() to find out what directory you're being invoked from.
You could also do it with a batch file. This is a little more flexible in that you can specify the exact name of the script and which Python interpreter should be used, and don't need to store the script in a directory in PYTHONPATH. Also, you don't need to worry about the file's name clashing with the name of a Python module. Simply put this line in a file:
C:\path\to\your\python.exe C:\path\to\your\script.py
Save it as (e.g.) doit.bat and copy it into the directories from which you want to invoke it. As before, your Python script can call os.getcwd() to get the directory. Or you can write it so your Python script accepts it as the first argument, and write your batch file like:
C:\path\to\your\python.exe C:\path\to\your\script.py %cd%
Another thing you can do with the batch file approach is add a pause command to the end so that the user is asked to press a key after the script runs, giving them the opportunity to read any output generated by the script. You could even make this conditional so that it only happens if an error occurs (which requires returning a proper exit code from the script). I'll leave that as an exercise. :-)
Is there a problem with modifying the script to take the directory to process as a command line argument?
You could then configure the different shortcuts to pass in the appropriate directory.
Type the following into a batch file (i.e. script.bat):
python \absolute\path\to\your\script.py %~dp0
pause
Then add these imports at the top of your python file script.py (if not already included):
import os
import sys
And add this to the bottom of the python file (or combine it with a similar statement):
if __name__ == "__main__":
# set current working directory:
if len(sys.argv) > 1:
os.chdir(sys.argv[1])
main()
replace main() with whatever function you want to call or code you want to run.
The following is how I came to my answer:
I tried using kindall's answer and had the following issues:
The first suggestion of storing the script somewhere in PYTHONPATH could not be applied to my situation because my script will be used on a server and needs to be independent of the client computer's python environment (besides having the required pip installations).
I tried calling my python script from a Windows Batch File which could be moved to a different location. Instead of the batch file's location being used as the current working directory, it was C:\Windows.
I tried passing %cd% as an argument to my python script, then setting that to be my CWD. This still resulted in a CWD of C:\Windows.
After reviewing the comments, I tried Eryk Sun's suggestion of instead passing %~dp0 as an argument to the python script. This resulted in the CWD being correctly set to the batch file's location.
I hope this helps others facing similar difficulties.

Hidden .db files using Python and SQLite3

I am using sqlite3 and python for a new website I am creating. The problem is, the "files_storage.db" file I am trying to create will not appear in any Windows 10 Folder Window, PyCharm's Directory View, nor will it appear via the command line interface.
The catch to this is, if I execute my python script multiple times, I get an error that states the database file already exists... So this file is somewhere, I guess it is a game of cat and mouse to find it.
I have ran into this problem before, but I have ALWAYS been able to find the file via the command line. Usually, I wouldn't both yall with such a question but, this is really irking me and I am going to run into serious issues when it comes time to put this baby on a server. :(
thanks in advance, and here's some screenshots I suppose.
You are using a relative file path.
Relative paths are converted to absolute ones by something like os.path.join(os.getcwd(), <relative path>). So they depend on the current working directory of the process.
Try to open it with an absolute path (starting with drive letter) to avoid any ambiguities.
If you use just a filename without a path, the file will be saved in whatever the current working directory of the Python interpreter is.
To see where the current working directory is, add the following code to the beginning of your program:
import os
print(os.getcwd())
You should then see the working directory in the output.
There is a setting for the current working directory in your IDE somewhere. See e.g. the answers to this question.
You can also do something like:
import os
path = os.path.expanduser("~") + '/Documents'
print(path)
This will allow you to access the directories for the current user. For me, this prints:
'/Users/thomasweeks/Documents'

How do I permanently set the current directory to the Desktop in Python?

Every time I want to open a text file that's on Desktop, I always need to change the directory in Python with these commands:
>>> import os
>>> os.chdir("C:/Users/Name/Desktop")
It's really annoying when I have to change it every time.
It's currently in C:\\Python34.
So how do I permanently set the working directory to Desktop?
Thanks in advance!
You can add the line to your PYTHONSTARTUP file. So when you start an interpreter os.chdir("C:/Users/Name/Desktop") will be run.
I have a startup.py in my home directory file with the following content:
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")
So every time I start ipython or a python shell those lines are executed.
Not 100 percent but I imagine setting the PYTHONSTARTUP="path_to_script" in your environment variables on windows should do the trick with the two lines in your question in the startup file.
So for your situation you can create a file lets call it startup.py and inside that file you put:
import os
os.chdir("C:/Users/Name/Desktop")
Then the steps to add environment variable PYTHONSTARTUP:
For windows 8:
From the Desktop, right-click the very bottom left corner of the screen to get the Power User Task Menu.
From the Power User Task Menu, click System.
Click the Advanced System Settings link in the left column.
Under System variables, click New.
Add PYTHONSTARTUP to Variable name.
Add the path of the Python file to Variable value and click OK. # <-path_to_startup.py
Click OK.
What you're talking about isn't a PATH (list of locations to look for executable/usable files), but a Current Working Directory (CWD).
If you're using python interactively (i.e. typing in each line), you'll probably have to chdir or similar every time you want to run it.
If you're running a python script (a .py file or similar), you can place that script on the Desktop, and its CWD will be Desktop when it starts (you might be able to place a shortcut to it on the desktop and get the same behavior; I'm not as certain of that).
Alternatively, you can write that boilerplate in a script that you source/load (via PYTHONSTARTUP or the first line of your code), or move the files you're interested in (or shortcuts to them) into a place that is next to your code.

Categories

Resources