1

l have two scripts:

main.py

import package.py

package.py

import os
print(os.path.basename(_file_))

my excepted output is main.py, but the fact is package.py.

So how can l get the running script's file name in a package script?

extra description:

the truth is, l have a decorator function in package.py. it will generate a file at current path and named as the file's name who called it

afraid.jpg
  • 965
  • 2
  • 14
  • 31
  • Since that code is within the file `package.py` you could just hard-code it (not saying there is no better solution). – Frank Sep 13 '18 at 03:12
  • 1
    What are you exactly trying to accomplish? I see that package.py calls the print, what's the link between package and main that you want to print? You want to print the name of a script as soon as you import it? – Rodolfo Donã Hosp Sep 13 '18 at 03:17
  • @RodolfoDonãHosp the really l wanna to do is, l packaged some function into package,py, but the function of one of these functions need to get current running python script's filename(in my usage, running python script is main.py). – afraid.jpg Sep 13 '18 at 03:29
  • 1
    import sys print sys.argv[0] See https://stackoverflow.com/questions/4152963/get-the-name-of-current-script-with-python – Igor P. Sep 13 '18 at 03:43
  • what is your expected output – Pyd Sep 13 '18 at 03:56
  • @pyd l have been said my excepted output is `main.py` in my description – afraid.jpg Sep 13 '18 at 04:05

4 Answers4

1

Try this

print(os.path.basename(__name__))
1

try:

main.py:

import package.py

package.py:

import sys
print(sys.argv[0])
sophic
  • 11
  • 1
1

You should be able to use arguments to work it out.

from sys import argv
print(argv[0])

The first argument listed will be the command used to execute your script. So if you're running ./main.py then that's what you'll get.

If you're running it via python (such as python main.py) then (at least according to my testing) you'll get the full path. You can use the tools in os.path to pluck out just the filename if required.

Shadow
  • 8,749
  • 4
  • 47
  • 57
0

If you are trying to get the entire path to the importing script, do this:

import os
import sys
# get working directory
dir = os.getcwd()
# get script path as passed to python
script = sys.argv[0]
# if path is not absolute, then join with current dir
importing_script = os.path.join(dir,script) if not os.path.isabs(script) else script

# Your importing script is...
print(importing_script)

Anthony M.
  • 98
  • 5