How does one acquire the directory of the Windows Shortcut calling a python script. I'd like to have multiple shortcuts in various places pointing to one script that I could edit if I wanted, but where the directory from which the script is called is accessible. Is this possible?
This script would likely then be compiled with py2exe or something, so if it is something that isn't possibly until THAT stage, I could go with that. Thanks!
The easiest solution is to just use a batch script instead of a shortcut.
All it needs is python C:\path\to\script\script.py, and the script will have the correct CWD.
The default when creating a shortcut on windows is for the Start in: property to be set to the folder the linked file resides in.
The script has no knowledge of the fact that it was called from a shortcut, let alone where that shortcut resides.
You can change the Start in: property of the shortcut to the path of the folder the shortcut resides in.
Then you can use os.getcwd() to get that path.
Unfortunately setting Start in: to . doesn't work.
In general you cannot obtain this information. You should use argv to switch behaviour of your script.
you can do so with
import os
print os.getcwd()
os.getcwd()
Return a string representing the current working directory.
Availability: Unix, Windows.
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.
So I have a Python program written, and what I am trying to do is to create windows shortcut to the program, and making sure that when running the shortcut, not only the software is ran but also the current directory that the shortcut is at would be passed as sys.argv, so that I could do something to it in the program. I know that for windows shortcut, you can do something like this:
"C:\Documents and Settings\Administrator\Desktop\hello.py" --somevalue
to pass in arguments to the target. I am wondering how could I make it work for my specific case? So for example, if we put the shortcut at Desktop, and run the shortcut, the Python software would start with sys.argv[1]="C:\Users\username\Desktop".
You can specify the current directory for the executed application in a .LNK, that is the normal way to do things if you depend on a specific directory.
If you for some reason actually need to get information about the .LNK you must call the GetStartupInfo Windows function (with ctypes I assume) and if the STARTF_TITLEISLINKNAME bit is set in STARTUPINFO.dwFlags then STARTUPINFO.lpTitle contains the path to the .LNK the user used to start the application.
I discovered that a script's "current working directory" is, initially, not the where the script is located, but rather where the user is when he/she runs the script.
If the script is at /Desktop/Projects/pythonProject/myscript.py, but I'm at /Documents/Arbitrary in my terminal when I run the script, then that's going to be it's present working directory, and an attempt at open('data.txt') is going to give File Not Found because it's not looking in the right directory.
So how is a script supposed to open files if it can't know where it's being run from? How is this handled?
My initial thought was to use absolute paths. Say my script needs to open data.txt which is stored alongside it in its package pythonProject. Then I would just say open('/Desktop/Projects/pythonProject/data.txt').
But then you can't ever move the project without editing every path in it, so this can't be the right solution.
Or is the answer simply that you must be in the directory where the script is located whenever you run the script? That doesn't seem right either.
Is there some simple manipulation for this that I'm not thinking of? Are you just supposed to os.chdir to the script's location at the beginning of the script?
Get the current file's directory path, using os.path.dirname, os.path.abspath, os.path.realpath, and the __file__ variable:
import os
file_dir = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
Then, to create cross-platform filepaths, use os.path.join():
os.path.join(file_dir, "test.txt")
Alternatively, you can change the current working directory to the running file's directory so you don't have to os.path.join every time:
os.path.chdir(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
Why use os.path.abspath and os.path.realpath? The inner realpath resolves symbolic links, while the abspath resolves relative paths. If you know for sure no symbolic links are being used, you can omit this inner realpath call.
A module's location is always available in the __file__ variable. You can use the functions in os.path (I'm mainly thinking of basedir and join) to transform module-relative paths to absolute paths
I have a quick question about the default working directly on python.
I am currently using the python 2.7. In this case the default working directly is the C:/Python27.
I want to change this permanently to another directory.
Even if we write down following on shell, the default working directory will go back to the original C:/Python27 automatically.
import os
os.chdir('a path')
Does any one know how to set up default directory permanently to "the path" which keeps the directory after the closing the shell?
This is a different question from how to change working directory just by the function temporarily.
Thank you so much for your help!!
The working directory of the python directory is the directory from which it was started. If from a console (cmd.exe) I do cd /some/dir and then start python, its working directory will be /some/dir.
If you want an interactive console started at a given directory you have some options:
Using a shortcut, you can change its Start in field, in the properties tab, to point to your target directory.
Use IPython instead, and add a startup script to the default profile so it always start at the target directory. IPython is an enhanced interactive with lots of useful features.
If you are running from a script and want to switch to the folder where you script is stored, you could use os.cd(os.path.dirname(__file__)).
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.
I have a python program which I compile down to a Windows .exe using py2exe.
Using Inno Setup, I create a Windows installer.
The nature of my program is such that it uses plugins which are later imported using the __import__() statement. These plugins are located in a 'plugins' folder, which itself is located as a subfolder of where my program's .exe file resides.
Now, to have the program find the plugins, it earlier had the following statement somwhere at the top of my file:
sys.path+= ['.']
However, this was not working well when the user started the program through Windows' start menu, because apparently the working folder was set to the start menu (instead of where the .exe is located). So '.' did not resolve to what I wanted.
I fixed it by changing the statement to the following, so that the __import__() statement also looks in the folder where the .exe is located (because argv[0] is the full path of the executable):
sys.path+= [os.path.dirname(sys.argv[0])]
However, I am not sure if I picked the right solution. Especially, because my program is meant to be cross-platform (Windows, OSX, Linux) and the sys.argv documentation says about argv[0] that 'it is operating system dependent whether this is a full pathname or not'.
Should I solve this differently, or is my approach OK?
In my compiled to .exe Qt programms, I'm using code very similar to yours:
def executable_path():
self_file = unicode(sys.argv[0], sys.getfilesystemencoding())
return os.path.realpath(os.path.dirname(self_file))
I'm using unicode because path may contain non ascii symbols.
sys.argv[0] it is operating system dependent whether this is a full pathname or not
os.path.realpath solves that problem.
Why not have a config file with the path to the plugins dir? This lets the user move it, and you can have one for each os. Stick it with the executable, or maybe a couple well used locations, ~ or /etc on linux, and %homepath% on windows.
I often use this:
os.chdir(sys.argv[0].rsplit(os.sep, 1)[0])
that makes runtime consistent with development environment, where you run your script from it's directory.
Please use __file__ of the module. You can write like
sys.path+=os.path.dirname(mymodule.__file__)
This will add your module's parent directory in sys.path.