[ python program doesn't work when opened by run ]
I'm using Windows 7 x64, when I open my program by Windows - run it does not work properly. It stars, but the commands does not work the way they do, when I double click it.
/run cmd /c start "" "C:\Python27\Scripts\bot.bat"
/run cmd /c start python "C:\Python27\Scripts\bot.py"
/run python "C:\Python27\Scripts\bot.py"
I tried these and all of them, failed. While a simple double click on the .bat file or the .py work.
The bat file just calls for the python file
@echo off
start "" "C:\Python27\Scripts\bot.py"
The error when I open it by Windows - Run is
[Errno 2] No such file or directory: 'list.txt'
list.txt is inside Scripts folder and when opened by double click it always worked.
Update
I open the files for read using
g = open("list.txt","r")
and again for write:
g = open("list.txt","w")
I've tried James solution and it worked, but since I have many methods using these, I will get a lot of work as it is not just find and replace, it envolves indentation and also the names of lists changes according which method.
Answer 1
You'll want to do something like this in your application:
import os
import sys
with open(os.path.join(os.path.dirname(sys.argv[0]), "lists.txt"), "r") as f:
# do something with lists.txt
This removes the assumption that lists.txt
will be in the current directory or similar.
Note: that sys.argv[0]
should be the "full absolute path" to the program being executed and hopefully C:\Python27\Scripts\bot.py
on your system.
Update: Alternative to using sys.argv[0]
(Thank you Alex Taylor) as a means of "determining your entrypoint's directory" you could also use __file__
which is a "global" in Python module(s) that is the "full path" to that module. The only caveat here is that this won't work if your "package" is zipped or otherwise an importable archive. See: __file__
Answer 2
Similar to James' answer, but using the __file__
macro as the way of getting the currently executing script:
import os.path
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'list.txt'), 'r') as list_file:
list_data = list_file.read()
The issue is that the working directory is set to the location you double-clicked from, but launching from the command line in the ways you have provided does not. Opening a command prompt to the location of the script and launching from there would also work since the file would be in the working directory.
The __file___
macro is generally considered to be the best way of determining a python script location.