Каталог сценариев python

I would like to see what is the best way to determine the current script directory in Python. I discovered that, due to the many ways of calling Python code, it is hard to find a good solution. Her...

First.. a couple missing use-cases here if we’re talking about ways to inject anonymous code..

code.compile_command()
code.interact()
imp.load_compiled()
imp.load_dynamic()
imp.load_module()
__builtin__.compile()
loading C compiled shared objects? example: _socket?)

But, the real question is, what is your goal — are you trying to enforce some sort of security? Or are you just interested in whats being loaded.

If you’re interested in security, the filename that is being imported via exec/execfile is inconsequential — you should use rexec, which offers the following:

This module contains the RExec class,
which supports r_eval(), r_execfile(),
r_exec(), and r_import() methods, which
are restricted versions of the standard
Python functions eval(), execfile() and
the exec and import statements. Code
executed in this restricted environment
will only have access to modules and
functions that are deemed safe; you can
subclass RExec add or remove capabilities as
desired.

However, if this is more of an academic pursuit.. here are a couple goofy approaches that you
might be able to dig a little deeper into..

Example scripts:

./deep.py

print ' >> level 1'
execfile('deeper.py')
print ' << level 1'

./deeper.py

print 't >> level 2'
exec("import sys; sys.path.append('/tmp'); import deepest")
print 't << level 2'

/tmp/deepest.py

print 'tt >> level 3'
print 'ttt I can see the earths core.'
print 'tt << level 3'

./codespy.py

import sys, os

def overseer(frame, event, arg):
    print "loaded(%s)" % os.path.abspath(frame.f_code.co_filename)

sys.settrace(overseer)
execfile("deep.py")
sys.exit(0)

Output

loaded(/Users/synthesizerpatel/deep.py)
>> level 1
loaded(/Users/synthesizerpatel/deeper.py)
    >> level 2
loaded(/Users/synthesizerpatel/<string>)
loaded(/tmp/deepest.py)
        >> level 3
            I can see the earths core.
        << level 3
    << level 2
<< level 1

Of course, this is a resource-intensive way to do it, you’d be tracing
all your code.. Not very efficient. But, I think it’s a novel approach
since it continues to work even as you get deeper into the nest.
You can’t override ‘eval’. Although you can override execfile().

Note, this approach only coveres exec/execfile, not ‘import’.
For higher level ‘module’ load hooking you might be able to use use
sys.path_hooks (Write-up courtesy of PyMOTW).

Thats all I have off the top of my head.

  1. HowTo
  2. Python How-To’s
  3. Как получить каталог текущих файлов …

Jinku Hu
30 Январь 2023
18 Апрель 2020

  1. Python получает рабочую директорию
  2. Python получает директорию файла скрипта

Как получить каталог текущих файлов сценариев на Python

Операцию с файлами и каталогами мы ввели в Python 3 basic tutorial. В этом разделе мы покажем, как получить относительный и абсолютный путь выполняющегося скрипта.

Python получает рабочую директорию

Функция os.getcwd() возвращает текущую рабочую директорию.

Если вы запустите её в Python idle в режиме ожидания, то в результате получите путь к Python IDLE.

Python получает директорию файла скрипта

Путь к файлу скрипта можно найти в global namespace с помощью специальной глобальной переменной __file__. Она возвращает относительный путь файла скрипта относительно рабочей директории.

В приведенных ниже примерах мы покажем вам, как использовать функции, которые мы только что ввели.

import os

wd = os.getcwd()
print("working directory is ", wd)

filePath = __file__
print("This script file path is ", filePath)

absFilePath = os.path.abspath(__file__)
print("This script absolute path is ", absFilePath)

path, filename = os.path.split(absFilePath)
print("Script file path is {}, filename is {}".format(path, filename))
absFilePath = os.path.abspath(__file__)

os.path.abspath(__file__) возвращает абсолютный путь заданного относительного пути.

path, filename = os.path.split(absFilePath)

Функция os.path.split() разделяет имя файла на чистый путь и чистое имя файла.

Jinku Hu avatar
Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

Ezoic

How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:

$ pwd
/tmp
$ python baz.py
running from /tmp 
file is baz.py

codeforester's user avatar

codeforester

37.2k16 gold badges107 silver badges132 bronze badges

asked Aug 18, 2009 at 21:02

Chris Bunch's user avatar

Chris BunchChris Bunch

86.4k37 gold badges124 silver badges126 bronze badges

1

__file__ is NOT what you are looking for. Don’t use accidental side-effects

sys.argv[0] is always the path to the script (if in fact a script has been invoked) — see http://docs.python.org/library/sys.html#sys.argv

__file__ is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0].

Example:

C:junkso>type junksoscriptpathscript1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()

C:junkso>type python26libsite-packageswhereutils.py
import sys, os
def show_where():
    print "show_where: sys.argv[0] is", repr(sys.argv[0])
    print "show_where: __file__ is", repr(__file__)
    print "show_where: cwd is", repr(os.getcwd())

C:junkso>python26python scriptpathscript1.py
script: sys.argv[0] is 'scriptpath\script1.py'
script: __file__ is 'scriptpath\script1.py'
script: cwd is 'C:\junk\so'
show_where: sys.argv[0] is 'scriptpath\script1.py'
show_where: __file__ is 'C:\python26\lib\site-packages\whereutils.pyc'
show_where: cwd is 'C:\junk\so'

oHo's user avatar

oHo

49.2k27 gold badges160 silver badges196 bronze badges

answered Aug 19, 2009 at 1:29

John Machin's user avatar

John MachinJohn Machin

80.3k11 gold badges139 silver badges185 bronze badges

7

This will print the directory in which the script lives (as opposed to the working directory):

import os
dirname, filename = os.path.split(os.path.abspath(__file__))
print "running from", dirname
print "file is", filename

Here’s how it behaves, when I put it in c:src:

> cd c:src
> python so-where.py
running from C:src
file is so-where.py

> cd c:
> python srcso-where.py
running from C:src
file is so-where.py

answered Aug 18, 2009 at 21:08

RichieHindle's user avatar

RichieHindleRichieHindle

267k47 gold badges354 silver badges396 bronze badges

4

import sys, os

file = sys.argv[0]
pathname = os.path.dirname(file)
print 'running from %s' % os.path.abspath(pathname)
print 'file is %s' % file

Check os.getcwd() (docs)

answered Aug 18, 2009 at 21:10

Nathan's user avatar

The running file is always __file__.

Here’s a demo script, named identify.py

print __file__

Here’s the results

MacBook-5:Projects slott$ python StackOverflow/identify.py 
StackOverflow/identify.py
MacBook-5:Projects slott$ cd StackOverflow/
MacBook-5:StackOverflow slott$ python identify.py 
identify.py

answered Aug 18, 2009 at 21:10

S.Lott's user avatar

S.LottS.Lott

380k79 gold badges505 silver badges775 bronze badges

1

I would suggest

import os, sys
print os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]

This way you can safely create symbolic links to the script executable and it will still find the correct directory.

answered Aug 19, 2009 at 11:24

0

The script name will (always?) be the first index of sys.argv:

import sys
print sys.argv[0]

An even easier way to find the path of your running script:

os.path.dirname(sys.argv[0])

David Mulder's user avatar

David Mulder

7,36511 gold badges44 silver badges60 bronze badges

answered Aug 18, 2009 at 21:10

WhatIsHeDoing's user avatar

WhatIsHeDoingWhatIsHeDoing

5291 gold badge6 silver badges20 bronze badges

3

The directory of the script which python is executing is added to sys.path
This is actually an array (list) which contains other paths.
The first element contains the full path where the script is located (for windows).

Therefore, for windows, one can use:

import sys
path = sys.path[0]
print(path)

Others have suggested using sys.argv[0] which works in a very similar way and is complete.

import sys
path = os.path.dirname(sys.argv[0])
print(path)

Note that sys.argv[0] contains the full working directory (path) + filename whereas sys.path[0] is the current working directory without the filename.

I have tested sys.path[0] on windows and it works. I have not tested on other operating systems outside of windows, so somebody may wish to comment on this.

answered Dec 1, 2018 at 17:06

D.L's user avatar

D.LD.L

3,7224 gold badges20 silver badges39 bronze badges

Aside from the aforementioned sys.argv[0], it is also possible to use the __main__:

import __main__
print(__main__.__file__)

Beware, however, this is only useful in very rare circumstances;
and it always creates an import loop, meaning that the __main__ will not be fully executed at that moment.

answered Oct 8, 2018 at 15:19

HoverHell's user avatar

HoverHellHoverHell

4,6793 gold badges20 silver badges23 bronze badges

How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:

$ pwd
/tmp
$ python baz.py
running from /tmp 
file is baz.py

codeforester's user avatar

codeforester

37.2k16 gold badges107 silver badges132 bronze badges

asked Aug 18, 2009 at 21:02

Chris Bunch's user avatar

Chris BunchChris Bunch

86.4k37 gold badges124 silver badges126 bronze badges

1

__file__ is NOT what you are looking for. Don’t use accidental side-effects

sys.argv[0] is always the path to the script (if in fact a script has been invoked) — see http://docs.python.org/library/sys.html#sys.argv

__file__ is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0].

Example:

C:junkso>type junksoscriptpathscript1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()

C:junkso>type python26libsite-packageswhereutils.py
import sys, os
def show_where():
    print "show_where: sys.argv[0] is", repr(sys.argv[0])
    print "show_where: __file__ is", repr(__file__)
    print "show_where: cwd is", repr(os.getcwd())

C:junkso>python26python scriptpathscript1.py
script: sys.argv[0] is 'scriptpath\script1.py'
script: __file__ is 'scriptpath\script1.py'
script: cwd is 'C:\junk\so'
show_where: sys.argv[0] is 'scriptpath\script1.py'
show_where: __file__ is 'C:\python26\lib\site-packages\whereutils.pyc'
show_where: cwd is 'C:\junk\so'

oHo's user avatar

oHo

49.2k27 gold badges160 silver badges196 bronze badges

answered Aug 19, 2009 at 1:29

John Machin's user avatar

John MachinJohn Machin

80.3k11 gold badges139 silver badges185 bronze badges

7

This will print the directory in which the script lives (as opposed to the working directory):

import os
dirname, filename = os.path.split(os.path.abspath(__file__))
print "running from", dirname
print "file is", filename

Here’s how it behaves, when I put it in c:src:

> cd c:src
> python so-where.py
running from C:src
file is so-where.py

> cd c:
> python srcso-where.py
running from C:src
file is so-where.py

answered Aug 18, 2009 at 21:08

RichieHindle's user avatar

RichieHindleRichieHindle

267k47 gold badges354 silver badges396 bronze badges

4

import sys, os

file = sys.argv[0]
pathname = os.path.dirname(file)
print 'running from %s' % os.path.abspath(pathname)
print 'file is %s' % file

Check os.getcwd() (docs)

answered Aug 18, 2009 at 21:10

Nathan's user avatar

The running file is always __file__.

Here’s a demo script, named identify.py

print __file__

Here’s the results

MacBook-5:Projects slott$ python StackOverflow/identify.py 
StackOverflow/identify.py
MacBook-5:Projects slott$ cd StackOverflow/
MacBook-5:StackOverflow slott$ python identify.py 
identify.py

answered Aug 18, 2009 at 21:10

S.Lott's user avatar

S.LottS.Lott

380k79 gold badges505 silver badges775 bronze badges

1

I would suggest

import os, sys
print os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]

This way you can safely create symbolic links to the script executable and it will still find the correct directory.

answered Aug 19, 2009 at 11:24

0

The script name will (always?) be the first index of sys.argv:

import sys
print sys.argv[0]

An even easier way to find the path of your running script:

os.path.dirname(sys.argv[0])

David Mulder's user avatar

David Mulder

7,36511 gold badges44 silver badges60 bronze badges

answered Aug 18, 2009 at 21:10

WhatIsHeDoing's user avatar

WhatIsHeDoingWhatIsHeDoing

5291 gold badge6 silver badges20 bronze badges

3

The directory of the script which python is executing is added to sys.path
This is actually an array (list) which contains other paths.
The first element contains the full path where the script is located (for windows).

Therefore, for windows, one can use:

import sys
path = sys.path[0]
print(path)

Others have suggested using sys.argv[0] which works in a very similar way and is complete.

import sys
path = os.path.dirname(sys.argv[0])
print(path)

Note that sys.argv[0] contains the full working directory (path) + filename whereas sys.path[0] is the current working directory without the filename.

I have tested sys.path[0] on windows and it works. I have not tested on other operating systems outside of windows, so somebody may wish to comment on this.

answered Dec 1, 2018 at 17:06

D.L's user avatar

D.LD.L

3,7224 gold badges20 silver badges39 bronze badges

Aside from the aforementioned sys.argv[0], it is also possible to use the __main__:

import __main__
print(__main__.__file__)

Beware, however, this is only useful in very rare circumstances;
and it always creates an import loop, meaning that the __main__ will not be fully executed at that moment.

answered Oct 8, 2018 at 15:19

HoverHell's user avatar

HoverHellHoverHell

4,6793 gold badges20 silver badges23 bronze badges

In this article, we will cover How to Get and Change the Current Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. ‘GFG.txt’ and if the file is not located in the directory of the script, Python raises an error.

The concept of the Current Working Directory (CWD) becomes important here. Consider the CWD as the folder, the Python is operating inside. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that a name-only reference will be successful only if the file is in the Python’s CWD.

Note: The folder where the Python script is running is known as the Current Directory. This may not be the path where the Python script is located.

What is the Python os module?

Python provides os module for interacting with the operating system. This module comes under Python’s standard utility module. All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.

Using os.getcwd() method to get Python Script location 

The os.getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.

Syntax of os.getcwd() method

Syntax: os.getcwd()

Parameter: No parameter is required.

Return Value: This method returns a string which represents the current working directory. 

Example 1: Get the current working directory using os.getcwd()

I have placed the Python file (test.py) inside /home/tuhingfg/Documents/Scripts/test.py. And running the Python Script from the Scripts folder.

Python3

import os

print("File location using os.getcwd():", os.getcwd())

Output:

File location using os.getcwd(): /home/tuhingfg/Documents/Scripts

Note: Using os.getcwd() doesn’t work as expected when running the Python code from different directory as the Python script.

Example 2: Unexpected result when running Python script from different directory other than script using os.getcwd()

Python3

import os

print("File location using os.getcwd():", os.getcwd())

Output:

Get Script location using os.getcwd()

Explanation: The Python script is placed inside /home/tuhingfg/Documents/Scripts. When we run the script from inside the same folder, it gives correct script location. But when we change our directory to some other place, it outputs the location of that directory. This is because, os.getcwd() considers the directory from where we are executing the script. Based on this, the result of os.getcwd() also varies.

Using os.path.realpath() method to get Python Script location 

os.path.realpath() can be used to get the path of the current Python script. Actually, os.path.realpath() method in Python is used to get the canonical path of the specified filename by eliminating any symbolic links encountered in the path. A special variable __file__ is passed to the realpath() method to get the path of the Python script.

Note: __file__ is the pathname of the file from which the module was loaded if it was loaded from a file.  

Syntax of os.path.realpath() method

Syntax: os.path.realpath(path)

Parameter: 

  • path: A path-like object representing the file system path. A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the canonical path. 
 

Example: Get the directory script path using __file__ special variable

Inside a Python script, we can use os.path.realpath() and __file__ special variable to get the location of the script. And the result obtained from this method doesn’t depend on the location of execution of the script.

Python3

import os

print("File location using os.getcwd():", os.getcwd())

print(f"File location using __file__ variable: {os.path.realpath(os.path.dirname(__file__))}")

Output:

Explanation: Here, the os.getcwd() and __file__ provides two different results. Since, we are executing the script from a different folder than the script, os.getcwd() output has changed according to the folder of execution of the script. But __file__ generates the constant result irrespective of the current working directory.

16.10.2020
Python

При работе с файлами в каталогах в Python всегда рекомендуется использовать абсолютные пути. Однако, если вы работаете с относительными путями, вам необходимо понимать концепцию текущего рабочего каталога и то, как найти или изменить текущий рабочий каталог. Абсолютный путь указывает расположение файла или каталога, начиная с корневого каталога, а относительный путь начинается с текущего рабочего каталога.

Когда вы запускаете сценарий Python, в качестве текущего рабочего каталога устанавливается каталог, из которого выполняется сценарий.

Модуль os python обеспечивает переносимый способ взаимодействия с операционной системой. Модуль является частью стандартной библиотеки Python и включает методы поиска и изменения текущего рабочего каталога.

Получение текущего рабочего каталога в Python

Метод getcwd() модуля os в Python возвращает строку, содержащую абсолютный путь к текущему рабочему каталогу. Возвращенная строка не включает завершающий символ косой черты.

Чтобы использовать методы модуля os, вы должны импортировать модуль в верхней части файла.

Ниже приведен пример, показывающий, как распечатать текущий рабочий каталог:

# Import the os module
import os

# Get the current working directory
cwd = os.getcwd()

# Print the current working directory
print("Current working directory: {0}".format(cwd))

# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

Результат будет выглядеть примерно так:

Current working directory: /home/linuxize/Desktop
os.getcwd() returns an object of type: <class 'str'>

Если вы хотите найти каталог, в котором находится скрипт, используйте os.path.realpath(__file__) . Он вернет строку, содержащую абсолютный путь к запущенному скрипту.

Изменение текущего рабочего каталога в Python

Чтобы изменить текущий рабочий каталог в Python, используйте метод chdir() .

Метод принимает один аргумент — путь к каталогу, в который вы хотите перейти. Аргумент path может быть абсолютным или относительным.

Вот пример:

# Import the os module
import os

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Change the current working directory
os.chdir('/tmp')

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

Результат будет выглядеть примерно так:

Current working directory: /home/linuxize/Desktop
Current working directory: /tmp

Аргумент, передаваемый методу chdir() должен быть каталогом, в противном случае NotADirectoryError исключение NotADirectoryError . Если указанный каталог не существует, возникает исключение FileNotFoundError . Если у пользователя, от имени которого выполняется сценарий, нет необходимых разрешений, возникает исключение PermissionError .

# Import the os module
import os

path = '/var/www'

try:
    os.chdir(path)
    print("Current working directory: {0}".format(os.getcwd()))
except FileNotFoundError:
    print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
    print("{0} is not a directory".format(path))
except PermissionError:
    print("You do not have permissions to change to {0}".format(path))

Выводы

Чтобы найти текущий рабочий каталог в Python, используйте os.getcwd() , а для изменения текущего рабочего каталога используйте os.chdir(path) .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Update 2018-11-28:

Here is a summary of experiments with Python 2 and 3. With

main.py — runs foo.py
foo.py — runs lib/bar.py
lib/bar.py — prints filepath expressions

| Python | Run statement       | Filepath expression                    |
|--------+---------------------+----------------------------------------|
|      2 | execfile            | os.path.abspath(inspect.stack()[0][1]) |
|      2 | from lib import bar | __file__                               |
|      3 | exec                | (wasn't able to obtain it)             |
|      3 | import lib.bar      | __file__                               |

For Python 2, it might be clearer to switch to packages so can use from lib import bar — just add empty __init__.py files to the two folders.

For Python 3, execfile doesn’t exist — the nearest alternative is exec(open(<filename>).read()), though this affects the stack frames. It’s simplest to just use import foo and import lib.bar — no __init__.py files needed.

See also Difference between import and execfile


Original Answer:

Here is an experiment based on the answers in this thread — with Python 2.7.10 on Windows.

The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax, i.e. —

print os.path.abspath(inspect.stack()[0][1])                   # C:filepathslibbar.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:filepathslib

Here’s to these being added to sys as functions! Credit to @Usagi and @pablog

Based on the following three files, and running main.py from its folder with python main.py (also tried execfiles with absolute paths and calling from a separate folder).

C:filepathsmain.py: execfile('foo.py')
C:filepathsfoo.py: execfile('lib/bar.py')
C:filepathslibbar.py:

import sys
import os
import inspect

print "Python " + sys.version
print

print __file__                                        # main.py
print sys.argv[0]                                     # main.py
print inspect.stack()[0][1]                           # lib/bar.py
print sys.path[0]                                     # C:filepaths
print

print os.path.realpath(__file__)                      # C:filepathsmain.py
print os.path.abspath(__file__)                       # C:filepathsmain.py
print os.path.basename(__file__)                      # main.py
print os.path.basename(os.path.realpath(sys.argv[0])) # main.py
print

print sys.path[0]                                     # C:filepaths
print os.path.abspath(os.path.split(sys.argv[0])[0])  # C:filepaths
print os.path.dirname(os.path.abspath(__file__))      # C:filepaths
print os.path.dirname(os.path.realpath(sys.argv[0]))  # C:filepaths
print os.path.dirname(__file__)                       # (empty string)
print

print inspect.getfile(inspect.currentframe())         # lib/bar.py

print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:filepathslibbar.py
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:filepathslib
print

print os.path.abspath(inspect.stack()[0][1])          # C:filepathslibbar.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:filepathslib
print

Update 2018-11-28:

Here is a summary of experiments with Python 2 and 3. With

main.py — runs foo.py
foo.py — runs lib/bar.py
lib/bar.py — prints filepath expressions

| Python | Run statement       | Filepath expression                    |
|--------+---------------------+----------------------------------------|
|      2 | execfile            | os.path.abspath(inspect.stack()[0][1]) |
|      2 | from lib import bar | __file__                               |
|      3 | exec                | (wasn't able to obtain it)             |
|      3 | import lib.bar      | __file__                               |

For Python 2, it might be clearer to switch to packages so can use from lib import bar — just add empty __init__.py files to the two folders.

For Python 3, execfile doesn’t exist — the nearest alternative is exec(open(<filename>).read()), though this affects the stack frames. It’s simplest to just use import foo and import lib.bar — no __init__.py files needed.

See also Difference between import and execfile


Original Answer:

Here is an experiment based on the answers in this thread — with Python 2.7.10 on Windows.

The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax, i.e. —

print os.path.abspath(inspect.stack()[0][1])                   # C:filepathslibbar.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:filepathslib

Here’s to these being added to sys as functions! Credit to @Usagi and @pablog

Based on the following three files, and running main.py from its folder with python main.py (also tried execfiles with absolute paths and calling from a separate folder).

C:filepathsmain.py: execfile('foo.py')
C:filepathsfoo.py: execfile('lib/bar.py')
C:filepathslibbar.py:

import sys
import os
import inspect

print "Python " + sys.version
print

print __file__                                        # main.py
print sys.argv[0]                                     # main.py
print inspect.stack()[0][1]                           # lib/bar.py
print sys.path[0]                                     # C:filepaths
print

print os.path.realpath(__file__)                      # C:filepathsmain.py
print os.path.abspath(__file__)                       # C:filepathsmain.py
print os.path.basename(__file__)                      # main.py
print os.path.basename(os.path.realpath(sys.argv[0])) # main.py
print

print sys.path[0]                                     # C:filepaths
print os.path.abspath(os.path.split(sys.argv[0])[0])  # C:filepaths
print os.path.dirname(os.path.abspath(__file__))      # C:filepaths
print os.path.dirname(os.path.realpath(sys.argv[0]))  # C:filepaths
print os.path.dirname(__file__)                       # (empty string)
print

print inspect.getfile(inspect.currentframe())         # lib/bar.py

print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:filepathslibbar.py
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:filepathslib
print

print os.path.abspath(inspect.stack()[0][1])          # C:filepathslibbar.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:filepathslib
print

Понравилась статья? Поделить с друзьями:
  • Каталитические праздники 2022
  • Катаев цветик семицветик сценарий мероприятия
  • Катаев белеет парус одинокий сценарий
  • Касьяны церковный праздник
  • Касым праздник гагаузов