I'm trying to iterate on inspect.stack() in order to get the file hierarchy.

A simple example:

for value in inspect.stack():
    print value[1]

The output will be:

C:\xxx\ATE\Utilities\Simulator\Simulator.py
C:\xxx\ATE\Utilities\Simulator\Simulator.py
C:\xxx\ATE\Utilities\Simulator\serial.py
C:\xxx\ATE\Utilities\Serial\SerialHandle\trunk\SerialHandle.py
C:/xxx/ATE/DUTDrivers/DD_SimulatorExample/DD_Example_Simulator.py

Now i'm removing the file names using string manipulations, and using the path names in my software.

Question:

Why there there are some paths with slash (\) and some with backslash (/)?

Note: I know i can do a simple string manipulation using replace to replace the backslash to slash or just use os.path.normpath(path) but i'm trying to understand why the inspect.stack module returns it that way?

有帮助吗?

解决方案

It seems that PyCharm starts DD_Example_Simulator.py using full path and forward slashes (/).

That's why you see forward slashes only in DD_Example_Simulator.py path (the rest of the paths are built by Python interpreter and thus have proper Windows backslashes). As a side note: using forward slashes is perfectly OK on Windows. Well, at least my copy of Windows doesn't mind the forward slashes.

Let's have an expirement using cmd.exe.

Let's create two files.

First:

// inspectso.py
import inspect

for value in inspect.stack():
    print value[1]

Second:

// inspect_so.py
import inspectso

The final step of the expirement: run these commands in cmd:

e:\Temp>c:/Python27/python.exe E:/temp/inspect_so.py
E:\temp\inspectso.py
E:/temp/inspect_so.py

e:\Temp>c:/Python27/python.exe E:\temp\inspect_so.py
E:\temp\inspectso.py
E:\temp\inspect_so.py

e:\Temp>c:/Python27/python.exe inspect_so.py
e:\Temp\inspectso.py
inspect_so.py

As we can see the path to inspect_so.py is printed as it was passed on command line and the path to inspectso.py is always severely backslashed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top