0

I'm making an evaluator for a type of extension called '.way'. To open the file, you have to go to the files properties, select 'Open with Way.exe' and then open the file.
This is Way.exe's code:

import os
currentname = os.path.basename(__file__)
print(currentname)

When I run test.way, it prints 'Way.py' (The script that the .exe file runs) instead of 'test.way'. How do I get it to print the current file's name?

martineau
  • 119,623
  • 25
  • 170
  • 301
ineedhelp
  • 23
  • 1
  • 8
  • 2
    The predefinded `__file__` variable is defined to be the name of the current script file. – martineau Sep 27 '20 at 17:18
  • So how can you get the current file name? Thanks for replying. – ineedhelp Sep 27 '20 at 17:20
  • Sorry, it's unclear to me what file you want to get the name of — please [edit] your question and try to be more clear about that. – martineau Sep 27 '20 at 17:23
  • 1
    Why would Python know to print `'test.way'`? How can it possibly know that's what to print? See how to create a [mcve]. – Peter Wood Sep 27 '20 at 17:28
  • 1
    Have a looks at [**`sys.argv`**](https://docs.python.org/3/library/sys.html#sys.argv). It contains the script name and any other parameters passed to the python interpreter on the command line. – Peter Wood Sep 27 '20 at 17:30
  • *"test.way" is the module and the script* is hard to understand. The way most of us use those terms, the running file is a program or a script, and when it is running or imported, it is a module. – BoarGules Sep 27 '20 at 17:32
  • @PeterWood Thank you! Your answer solved my problem. If you could post it as an answer, I would love to check your post. – ineedhelp Sep 27 '20 at 17:35
  • I don't really want to answer the question as it needs improving drastically. It should be closed really. It won't help anyone else find the solution in future, as it's not a good statement of the problem which `sys.argv` solves. – Peter Wood Sep 27 '20 at 17:39

2 Answers2

0

Please try this:

from pathlib import Path
print(Path(__file__).resolve())

more details can be found in https://docs.python.org/3/library/pathlib.html

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Shree H
  • 16
0

I think I faced the same problem and this fixed it. Hopefully this helps

The following code snippet was referred from here

import os
import sys

# determine if application is a script file or frozen exe        
if getattr(sys, 'frozen', False):
    file_path = os.path.realpath(sys.executable)
elif __file__:
    file_path = os.path.realpath(__file__)
    
currentname = os.path.basename(file_path)
Muhid
  • 91
  • 5