0

Environment Python 3.9.6; Windows 10

Q1. Why do I get different results when using 'sys.argv'?

Full path of the script file >> "C:\example\test.py"

Code

import sys
print(sys.argv[0])

Then below are the results.

If I execute it via CMD like "python test.py",

test.py

If I execute it via IDLE or VS CODE,

C:\example\test.py

Q2. What is the best way to get the directory of a 'main' script file?

I need "SOMETHING_HERE" below that gives "C:\example" as a result.

if __name__ == "__main__":
    result = SOMETHING_HERE()
    print(result)

"sys.argv" is not an option regarding the problem in Q1. Neither is "os.getcwd()" because it literally gives 'current working folder' which is not the exact result I need. Is there any other option that I can get the directory safely?

sssbbbaaa
  • 204
  • 2
  • 12

1 Answers1

2

From whithin your script you can do:

from pathlib import Path
print (Path(__file__))

Using Path will allow you to inspect the path if you need to further process it (folder location, ....)

Typicall you can do:

parent_folder = Path(__file__).parent

See more here: https://docs.python.org/3/library/pathlib.html

Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • See [How to Answer](https://stackoverflow.com/help/how-to-answer), including the section _Answer Well-Asked Questions_, and the bullet point therein regarding questions that "have been asked and answered many times before". – Charles Duffy Nov 17 '21 at 14:04
  • The existing answers are already linked to the question -- scroll up to the very top. – Charles Duffy Nov 17 '21 at 14:12
  • (I'm less concerned about helping the OP, and more concerned about helping people who are searching via Google -- closing duplicates _as_ duplicates means we don't have a bunch of half-answered questions in search results, but instead have a smaller number of _comprehensively_-answered questions; that said, that same principle helps the OP too -- getting pointed to a preexisting instance of their question that has had more eyes reviewing, commenting on, editing, improving, &c. its answers means they get better-quality assistance, even if not so customized). – Charles Duffy Nov 17 '21 at 14:15
  • See https://stackoverflow.blog/2011/01/05/the-wikipedia-of-long-tail-programming-questions/, from nearer the site's founding, explaining the rationale behind the approach to closing duplicates (while keeping those closed, duplicate questions in the knowledgebase to act as pointers towards the canonical instance with its high-quality answers). – Charles Duffy Nov 17 '21 at 14:16