Search code examples
pythonwindowspython-2.7ircmirc

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.


Solution

  • 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.