Obtain the path of the script file in Python.

Source: Internet
Author: User

In python, how does one obtain the path of the script file?

First, we do not obtain the "current path", that is, OS. getcwd ()

This includes two obfuscation problems: first, obtaining the path of the current script file and second, obtaining the path of the script that starts the python interpreter.

Obtain the path of the current script file. The solution is 1, 2, and 3.

Obtain the path of the script file that starts the python interpreter. Solution: 4

When the current script is directly run (instead of called as a module), the results of the two problems are the same.

After you use cx_freeze to convert the script to an executable file, each solution will encounter its own problems and cannot correctly obtain the current file path in all circumstances. So we combined several methods and got solution 5, which solved all the problems.

 
1. Obtain the path of the script that calls this function. functions that can be called across modules and files:
// TBC: there is no problem when using the python interpreter to run the program. If there is a problem after compiling it into the EXE, the "current path" is displayed, but I don't know why. I printed inspect. Stack () and found that all files are correct, but the paths are the "current path" of the call. I don't know why?

 

# Function: Get the directory of script that callthis Function
# Usage: Path = script_path ()
Def script_path ():
Import inspect, OS
Caller_file = inspect. Stack () [1] [1] # caller's filename
Return OS. Path. abspath (OS. Path. dirname (caller_file) # path

 

2. Obtain the script path for defining the function. Copy multiple files if multiple files are used:

 

# Function: Get absolute directory of the file
# In which this function defines
# Usage: Path = script_path ()
# Note: Please copy the function to target script,
# Don't use it like <module>. script_path ()
Def script_path ():
Import inspect, OS
This_file = inspect. GetFile (inspect. currentframe ())
Return OS. Path. abspath (OS. Path. dirname (this_file ))

 

3. Use the built-in member variables of the module, but an error will be reported after the file is compiled into an executable file by cx_freeze, indicating that the variable definition cannot be found (or the built-in module has no corresponding member ):

 

# Warning: After compiling as EXE, the error "_ file _ definition cannot be found" is returned.
# Usage: Path = script_path (_ file __)
Def script_path (file_macro ):
Return OS. Path. abspath (OS. Path. dirname (file_macro ))

 

# Warning: After compiling as EXE, the system reports the following error: the module does not have the _ file _ attribute.
# Usage: Path = script_path (_ name __)
Def script_path (_ name __):
Return OS. Path. abspath (OS. Path. dirname (
SYS. modules [_ name _]. _ file __))

 

# Warning: After compiling as EXE, an exception is thrown: the module is a built-in module and cannot be used to get the file name using GetFile
# Usage: Path = script_path (_ name __)
Def script_path (_ name __):
Import inspect
Return OS. Path. abspath (inspect. GetFile (SYS. modules [_ name _])

 

4. Obtain the script path for starting the python Interpreter:

 

Def script_path ():
Path = OS. Path. realpath (SYS. path [0])
If OS. Path. isfile (PATH ):
Path = OS. Path. dirname (PATH)
Return OS. Path. abspath (PATH)

 

Def script_path ():
Path = OS. Path. realpath (SYS. argv [0])
If OS. Path. isfile (PATH ):
Path = OS. Path. dirname (PATH)
Return OS. Path. abspath (PATH)

 

5. Combine the above methods to solve the problem: if it is in an executable file, the path of the executable file is returned. If it is in the script, the path of the script that calls the function is returned.

However, there is also a problem. I found that the paths recorded by inspect. Stack () are relative paths, relative to OS. getcwd () at startup (). Therefore, if OS. chdir () is used, an error occurs.

 

# Function: Get directory of current script, if script is built
# Into an executable file, get directory of the excutable File
Def current_file_directory ():
Import OS, sys, inspect
Path = OS. Path. realpath (SYS. path [0]) # interpreter starter's path
If OS. Path. isfile (PATH): # starter is excutable File
Path = OS. Path. dirname (PATH)
Return OS. Path. abspath (PATH) # Return excutable file's directory
Else: # starter is Python script
Caller_file = inspect. Stack () [1] [1] # function caller's filename
Return OS. Path. abspath (OS. Path. dirname (caller_file) # Return function caller's file's directory

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.