1

l have two scripts:

main.py

import package.py

package.py

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

My expected output is main.py, but I'm getting package.py.

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

extra description:

The truth is, I 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.

6
  • Since that code is within the file package.py you could just hard-code it (not saying there is no better solution). Commented Sep 13, 2018 at 3: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? Commented Sep 13, 2018 at 3: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). Commented Sep 13, 2018 at 3:29
  • 1
    import sys print sys.argv[0] See stackoverflow.com/questions/4152963/… Commented Sep 13, 2018 at 3:43
  • what is your expected output Commented Sep 13, 2018 at 3:56

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

print(os.path.basename(__name__))

1 Comment

No, it failed, still print package.py
1

try:

main.py:

import package.py

package.py:

import sys
print(sys.argv[0])

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.