1

When ran from a terminal, sys.argv[0] is the path of current script, but in python interactive that variable points to "/some/path/ipykernel_launcher.py" which is a temporary file.

How do I get the path of current script (which I am editing in vscode)? I need this information because whenever I create a file, I automatically log which script created it. For that, I overload the open() function to automatically log the creation. But when file is created from a python interactive session, I am missing such information.

3
  • Maybe os.getcwd()? Commented May 20, 2021 at 18:53
  • Use the __file__ variable or the inspect module. Already answered here. Commented May 20, 2021 at 18:59
  • Thanks @koorkevani! The inspect strategy in that answer doesn't work, but __file__ does! Commented May 24, 2021 at 6:46

2 Answers 2

1
import os

print(os.getcwd())

I think that's what you want. It prints the current working directory.

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

1 Comment

Sorry, but that gives the execution path, which, by the way, I usually set with os.chdir(some_dir) . It is true that at start of the interactive session, the os.getcwd() is that of the script. ... Anyway, I am missing the filename.
0

The answer that works for me, obtained from How do I get the path and name of the file that is currently executing? is this:

os.path.realpath(__file__)

I tried all other suggestions, but didn't work.

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.