Hướng dẫn python get network drive path - python lấy đường dẫn ổ đĩa mạng

Nếu tôi sử dụng các mục sau để lấy danh sách tất cả các ổ đĩa được kết nối:

available_drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists['%s:' % d]]

Làm thế nào để tôi có được đường dẫn UNC của các ổ đĩa được kết nối?

import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
2 Chỉ trả về
import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
3 thay vì
import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
4

Đã hỏi ngày 7 tháng 7 năm 2017 lúc 12:24Jul 7, 2017 at 12:24

3

Sử dụng Win32WNet từ PyWin32 để chuyển đổi các chữ cái ổ đĩa của bạn. Ví dụ:

import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]

Điều này mang lại cho tôi một cái gì đó như thế này khi tôi chạy nó:

C:\test>python get_unc.py i:\some\path
\\machine\test_share\some\path

Đã trả lời ngày 14 tháng 7 năm 2017 lúc 12:10Jul 14, 2017 at 12:10

Peter Brittainpeter BrittainPeter Brittain

13.3k3 Huy hiệu vàng40 Huy hiệu bạc54 Huy hiệu đồng3 gold badges40 silver badges54 bronze badges

3

Đây là cách làm điều đó trong Python ≥ 3,4, không có sự phụ thuộc!*

from pathlib import Path

def unc_drive[file_path]:
    return str[Path[file_path].resolve[]]

*Lưu ý: Tôi vừa tìm thấy một tình huống trong đó phương pháp này thất bại. Một trong những cổ phiếu mạng của công ty tôi có thiết lập quyền sao cho phương pháp này tăng

import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
5. Trong trường hợp này,
import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
6 là một dự phòng phù hợp.

Đã trả lời ngày 1 tháng 8 năm 2019 lúc 0:00Aug 1, 2019 at 0:00

Sử dụng

import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
7 và mã được hiển thị trong câu trả lời đầu tiên trong bài đăng này: Nhận tên máy tính đầy đủ từ ký tự ổ đĩa mạng trong Python, có thể nhận đường dẫn ổ đĩa cho mỗi ổ đĩa mạng hoặc một số ít được chọn.

Hàm

import win32wnet
import sys

print[win32wnet.WNetGetUniversalName[sys.argv[1], 1]]
8 được đưa ra sẽ gây ra lỗi nếu ổ đĩa không phải là ổ đĩa mạng, các ổ đĩa cục bộ hoặc có thể tháo rời, điều này có thể được tính

# your drive list
available_drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists['%s:' % d]]
for drive in available_drives:
    try:
        # function from linked post
        print[get_connection[drive]]
    except WindowsError: # thrown from local drives
        print['{} is a local drive'.format[drive]]

Đã trả lời ngày 10 tháng 7 năm 2017 lúc 15:31Jul 10, 2017 at 15:31

NJOOSSENJOOSSEnjoosse

5493 Huy hiệu bạc8 Huy hiệu Đồng3 silver badges8 bronze badges

Vấn đề37993

Được tạo vào năm 2019-08-31 08:04 bởi CgoHlke, lần cuối đã thay đổi 2022-04-11 14:59 bởi Quản trị viên. Vấn đề giờ đã kết thúc.2019-08-31 08:04 by cgohlke, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Tin nhắn [7] MSG350910 - [Xem]Tác giả: Christoph Gohlke [Cgohlke]Ngày: 2019-08-31 08:04 MSG350916 - [Xem]Tác giả: Eryk Sun [Eryksun] **
Ngày: 2019-08-31 12:54 MSG350936 - [Xem]Tác giả: Steve Dower [Steve.Dower] **
Ngày: 2019-09-01 02:41 MSG350937 - [Xem]Tác giả: Steve Dower [Steve.Dower] **
Ngày: 2019-09-01 02:41 MSG350937 - [Xem]Tác giả: Eryk Sun [Eryksun] **
Ngày: 2019-08-31 12:54 MSG350936 - [Xem]Tác giả: Steve Dower [Steve.Dower] **
Ngày: 2019-09-01 02:41 MSG350937 - [Xem]Tác giả: Eryk Sun [Eryksun] **
Ngày: 2019-08-31 12:54
Re //bugs.python.org/issue9949:

Is it intended that Python-3.8.0b4 now also resolves mapped network drives and drives created with `subst`? 

I would not expect this from the documentation at //docs.python.org/3.8/library/os.path.html#os.path.realpath. The documentation refers to symbolic links and junctions, which are different from mapped network and subst drives [AFAIU].

For example, mapping `\\SERVER\Programs` as `X:` drive:

```
Python 3.8.0b4 [tags/v3.8.0b4:d93605d, Aug 29 2019, 23:21:28] [MSC v.1916 64 bit [AMD64]] on win32
>>> import sys, os
>>> sys.executable
'X:\\Python38\\python.exe'
>>> os.path.realpath[sys.executable]
'\\\\SERVER\\Programs\\Python38\\python.exe'
```

```
Python 3.7.4 [tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20] [MSC v.1916 64 bit [AMD64]] on win32
>>> import sys, os
>>> sys.executable
'X:\\Python37\\python.exe'
>>> os.path.realpath[sys.executable]
'X:\\Python37\\python.exe'
```

It seems this change causes an error in pytest-5.1.2 during numpy-1.17.1 tests:

```
X:\Python38>python.exe -c"import numpy;numpy.test[]"
NumPy version 1.17.1
NumPy relaxed strides checking option: True

============================================= ERRORS ==============================================
__________________________________ ERROR collecting test session __________________________________
lib\site-packages\_pytest\config\__init__.py:440: in _importconftest
    return self._conftestpath2mod[conftestpath]
E   KeyError: local['\\\\SERVER\\programs\\python38\\lib\\site-packages\\numpy\\conftest.py']

During handling of the above exception, another exception occurred:
lib\site-packages\_pytest\config\__init__.py:446: in _importconftest
    mod = conftestpath.pyimport[]
lib\site-packages\py\_path\local.py:721: in pyimport
    raise self.ImportMismatchError[modname, modfile, self]
E   py._path.local.LocalPath.ImportMismatchError: ['numpy.conftest', 'X:\\Python38\\lib\\site-packages\\numpy\\conftest.py', local['\\\\SERVER\\programs\\python38\\lib\\site-packages\\numpy\\conftest.py']]

During handling of the above exception, another exception occurred:
lib\site-packages\_pytest\runner.py:220: in from_call
    result = func[]
lib\site-packages\_pytest\runner.py:247: in 
    call = CallInfo.from_call[lambda: list[collector.collect[]], "collect"]
lib\site-packages\_pytest\main.py:485: in collect
    yield from self._collect[arg]
lib\site-packages\_pytest\main.py:512: in _collect
    col = self._collectfile[pkginit, handle_dupes=False]
lib\site-packages\_pytest\main.py:581: in _collectfile
    ihook = self.gethookproxy[path]
lib\site-packages\_pytest\main.py:424: in gethookproxy
    my_conftestmodules = pm._getconftestmodules[fspath]
lib\site-packages\_pytest\config\__init__.py:420: in _getconftestmodules
    mod = self._importconftest[conftestpath]
lib\site-packages\_pytest\config\__init__.py:454: in _importconftest
    raise ConftestImportFailure[conftestpath, sys.exc_info[]]
E   _pytest.config.ConftestImportFailure: [local['\\\\SERVER\\programs\\python38\\lib\\site-packages\\numpy\\conftest.py'], [, ImportMismatchError['numpy.conftest', 'X:\\Python38\\lib\\site-packages\\numpy\\conftest.py', local['\\\\SERVER\\programs\\python38\\lib\\site-packages\\numpy\\conftest.py']], ]]
!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1 error in 16.39s
```
>    >>> sys.executable
>    'X:\\Python38\\python.exe'
>    >>> os.path.realpath[sys.executable]
>    '\\\\SERVER\\Programs\\Python38\\python.exe'

Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

> different from mapped network and subst drives [AFAIU].

Mapped and subst drives are implemented as object-manager symlinks to file-system directories. For example, a subst drive "S:" might target a local directory such as r"\??\C:\Temp\Subst", and a mapped drive "M:" for an SMB share might target a path such as r"\Device\LanmanRedirector\;M:\Server\Share\Temp\Mapped". 

The root directory of these drives does not behave like a real root directory unless the drive targets the root of a volume or UNC share, such as "\\??\\C:\\" or r"\Device\LanmanRedirector;M:\Server\Share".

This means that in many cases it's possible to evaluate a relative symlink that traverses above the drive root via ".." components. Say we have a directory r"C:\Temp\Subst" that contains a relative symlink "foo_link" that targets r"..\foo". If we map "S:" to r"C:\Temp\Subst", then r"S:\foo_link" opens r"C:\Temp\foo". Similarly if we map r"\\localhost\C$\Temp\Subst" to "M:", then r"M:\foo_link" opens r"C:\Temp\foo".

In the above case, if we're using relpath[] to compute the relative path to the "foo" target, I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.
Is this an issue or a mismatched expectation?

Tests that assume realpath[] on Windows is the equivalent of abspath[] are of course going to fail when we fix realpath[], and that's kind of what this one looks like. Just because it doesn't have a direct Unix equivalent doesn't mean that any particular behavior is any better.

> Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

I don't think this necessarily follows. There's nowhere in the documentation that says that sys.executable is even a valid path, let alone the final path.

> I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.

Cross-drive relative paths are fine though - they are just absolute paths :]

>  The documentation refers to symbolic links and junctions, which are different from mapped network and subst drives [AFAIU].

If we can easily tell the difference between directory junctions and mapped drives, given that they are both identical types of reparse points, then we can make readlink[] only read directory junctions. I need a specific algorithm for telling the difference though, not just lists of examples of things that "should" work [without any rationale for why they ought to work].
Is this an issue or a mismatched expectation?

Tests that assume realpath[] on Windows is the equivalent of abspath[] are of course going to fail when we fix realpath[], and that's kind of what this one looks like. Just because it doesn't have a direct Unix equivalent doesn't mean that any particular behavior is any better.

> Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

I don't think this necessarily follows. There's nowhere in the documentation that says that sys.executable is even a valid path, let alone the final path.

> I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.

Cross-drive relative paths are fine though - they are just absolute paths :]

>  The documentation refers to symbolic links and junctions, which are different from mapped network and subst drives [AFAIU].

If we can easily tell the difference between directory junctions and mapped drives, given that they are both identical types of reparse points, then we can make readlink[] only read directory junctions. I need a specific algorithm for telling the difference though, not just lists of examples of things that "should" work [without any rationale for why they ought to work].
>    >>> sys.executable
>    'X:\\Python38\\python.exe'
>    >>> os.path.realpath[sys.executable]
>    '\\\\SERVER\\Programs\\Python38\\python.exe'

Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

> different from mapped network and subst drives [AFAIU].

Mapped and subst drives are implemented as object-manager symlinks to file-system directories. For example, a subst drive "S:" might target a local directory such as r"\??\C:\Temp\Subst", and a mapped drive "M:" for an SMB share might target a path such as r"\Device\LanmanRedirector\;M:\Server\Share\Temp\Mapped". 

The root directory of these drives does not behave like a real root directory unless the drive targets the root of a volume or UNC share, such as "\\??\\C:\\" or r"\Device\LanmanRedirector;M:\Server\Share".

This means that in many cases it's possible to evaluate a relative symlink that traverses above the drive root via ".." components. Say we have a directory r"C:\Temp\Subst" that contains a relative symlink "foo_link" that targets r"..\foo". If we map "S:" to r"C:\Temp\Subst", then r"S:\foo_link" opens r"C:\Temp\foo". Similarly if we map r"\\localhost\C$\Temp\Subst" to "M:", then r"M:\foo_link" opens r"C:\Temp\foo".

In the above case, if we're using relpath[] to compute the relative path to the "foo" target, I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.
Is this an issue or a mismatched expectation?

Tests that assume realpath[] on Windows is the equivalent of abspath[] are of course going to fail when we fix realpath[], and that's kind of what this one looks like. Just because it doesn't have a direct Unix equivalent doesn't mean that any particular behavior is any better.

> Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

I don't think this necessarily follows. There's nowhere in the documentation that says that sys.executable is even a valid path, let alone the final path.

> I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.

Cross-drive relative paths are fine though - they are just absolute paths :]

>  The documentation refers to symbolic links and junctions, which are different from mapped network and subst drives [AFAIU].

If we can easily tell the difference between directory junctions and mapped drives, given that they are both identical types of reparse points, then we can make readlink[] only read directory junctions. I need a specific algorithm for telling the difference though, not just lists of examples of things that "should" work [without any rationale for why they ought to work].
>    >>> sys.executable
>    'X:\\Python38\\python.exe'
>    >>> os.path.realpath[sys.executable]
>    '\\\\SERVER\\Programs\\Python38\\python.exe'

Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

> different from mapped network and subst drives [AFAIU].

Mapped and subst drives are implemented as object-manager symlinks to file-system directories. For example, a subst drive "S:" might target a local directory such as r"\??\C:\Temp\Subst", and a mapped drive "M:" for an SMB share might target a path such as r"\Device\LanmanRedirector\;M:\Server\Share\Temp\Mapped". 

The root directory of these drives does not behave like a real root directory unless the drive targets the root of a volume or UNC share, such as "\\??\\C:\\" or r"\Device\LanmanRedirector;M:\Server\Share".

This means that in many cases it's possible to evaluate a relative symlink that traverses above the drive root via ".." components. Say we have a directory r"C:\Temp\Subst" that contains a relative symlink "foo_link" that targets r"..\foo". If we map "S:" to r"C:\Temp\Subst", then r"S:\foo_link" opens r"C:\Temp\foo". Similarly if we map r"\\localhost\C$\Temp\Subst" to "M:", then r"M:\foo_link" opens r"C:\Temp\foo".

In the above case, if we're using relpath[] to compute the relative path to the "foo" target, I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.
MSG350936 - [Xem]Tác giả: Steve Dower [Steve.Dower] *Ngày: 2019-09-01 02:41
Is this an issue or a mismatched expectation?

Tests that assume realpath[] on Windows is the equivalent of abspath[] are of course going to fail when we fix realpath[], and that's kind of what this one looks like. Just because it doesn't have a direct Unix equivalent doesn't mean that any particular behavior is any better.

> Unix Python resolves the executable path with repeated _Py_wreadlink calls. Windows Python should do something similar to ensure the consistency of sys.executable with realpath[sys.executable].

I don't think this necessarily follows. There's nowhere in the documentation that says that sys.executable is even a valid path, let alone the final path.

> I think we want relpath[realpath['C:/Temp/foo'], realpath['S:/']] to succeed as r"..\foo". I don't think we want it to fail as a cross-drive relative path.

Cross-drive relative paths are fine though - they are just absolute paths :]

>  The documentation refers to symbolic links and junctions, which are different from mapped network and subst drives [AFAIU].

If we can easily tell the difference between directory junctions and mapped drives, given that they are both identical types of reparse points, then we can make readlink[] only read directory junctions. I need a specific algorithm for telling the difference though, not just lists of examples of things that "should" work [without any rationale for why they ought to work].
MSG350937 - [Xem]
Ngày: 2019-09-01 02:42________số 8bộ MSG350946 - [Xem]
Ngày: 2019-09-01 11:16EryksunbộNosy: + eryksunmessages: + msg350916
2019-08-31 & NBSP; 08: 04: 35Steve.DowerbộTin nhắn: + MSG350936
resolution: not a bug
messages: + msg351780

2019-08-31 & NBSP; 12: 54: 25

EryksunEryksunbộNosy: + eryksunmessages: + msg350916
2019-08-31 & NBSP; 08: 04: 35Steve.DowerbộTin nhắn: + MSG350937
2019-09-01 & NBSP; 02: 41: 45Steve.DowerbộTin nhắn: + MSG350936
2019-08-31 & NBSP; 12: 54: 25EryksunbộTin nhắn: + MSG350936
messages: + msg350916
2019-08-31 & NBSP; 12: 54: 25EryksunNosy: + eryksunmessages: + msg350916

Làm cách nào để tìm đường dẫn của ổ đĩa mạng?

Thông qua File Explorer để kiểm tra đường dẫn của ổ đĩa mạng bằng Trình khám phá tệp, nhấp vào 'PC này' trên bảng điều khiển bên trái trong Explorer.Sau đó bấm đúp vào ổ đĩa được ánh xạ trong 'Vị trí mạng'.Đường dẫn của ổ đĩa mạng được ánh xạ có thể được nhìn thấy ở phía trên.click on 'This PC' on the left panel in Explorer. Then double-click the mapped drive under 'Network Locations'. The path of the mapped network drive can be seen at the top.

Làm thế nào để bạn tìm thấy đường dẫn của một ổ đĩa trong Python?

Cách dễ dàng nhất là: từ đường dẫn nhập pathlib root = path [__ file __]. Anchor # 'C: \' hoặc '\' trên Unix.from pathlib import Path root = Path[__file__]. anchor # 'C:\' or '\' on unix.

Làm cách nào để sử dụng đường dẫn UNC?

Một đường dẫn UNC sử dụng dấu gạch chéo đôi hoặc dấu gạch chéo ngược để đi trước tên của máy tính.Đường dẫn [đĩa và thư mục] trong máy tính được phân tách bằng một dấu gạch chéo hoặc dấu gạch chéo, như trong các ví dụ sau.Lưu ý rằng trong ví dụ DOS/Windows, các chữ cái ổ đĩa [c :, d :, v.v.] không được sử dụng trong tên UNC.uses double slashes or backslashes to precede the name of the computer. The path [disk and directories] within the computer are separated with a single slash or backslash, as in the following examples. Note that in the DOS/Windows example, drive letters [c:, d:, etc.] are not used in UNC names.

Đường dẫn hệ điều hành là gì?

đường dẫn.Phương thức realpath [] trong python được sử dụng để có được đường dẫn chính tắc của tên tệp được chỉ định bằng cách loại bỏ bất kỳ liên kết tượng trưng nào gặp trong đường dẫn.Cú pháp: OS.Path.RealPath [Path]used to get the canonical path of the specified filename by eliminating any symbolic links encountered in the path. Syntax: os.path.realpath[path]

Bài Viết Liên Quan

Chủ Đề