如何区分本地文件系统路径和SSH上的文件系统路径?

2024-09-21 03:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在Linux上的Python中,一方面,我需要区分本地文件系统路径a la/mnt/data/wherever/%Y-%m-%d.txt或{},而SSH“paths”auser@host1:/data/bla.txt或{}。在

我怎样才能有效地做到这一点?在

编辑:在我的示例中,没有文件/mnt/data/wherever/%Y-%m-%d.txt,因为{}等只是占位符。因此,检查具有给定名称的文件/目录是否存在是行不通的。在


Tags: 文件路径txt编辑datalinuxsshla
2条回答

唯一的方法是使用启发式方法,因为ssh路径也是有效的文件名(尽管非常奇怪)。在

根据scp文档:

File names may contain a user and host specification to indicate that the file is to be copied to/from that host. Local file names can be made explicit using absolute or relative pathnames to avoid scp treating file names containing ‘:’ as host specifiers.

所以检查它们是否以显式路径开始,或者在正确的位置没有冒号。然后假设它是本地路径,否则假设它是远程路径。在

示例:

pattern = '(\.?/|/)|(^:?[^:]*$)'
re.match(pattern, ":home/test") # match, is a local path
re.match(pattern, "user@host:blah") # no match

你可以这样做-

  1. 首先在本地文件系统中签入一个路径X(这说明了像-user@host1:/data/bla.txt)这样的路径。在
  2. 如果路径X不存在于本地文件系统中,则检查SSH路径Y(另外还要检查“@”和“:”,因为否则该文件在任何计算机中都不存在)。在

使用glob根据模式列出文件。在

>>> import glob
>>> glob.glob('/mnt/data/wherever/*.txt')   # all txt files within the directory will be listed

如果路径是现有的常规文件,^{}返回True。所以它用于检查文件是否已经存在并且不支持通配符。glob可以。 要检查路径是否是本地文件系统中的现有文件,请使用:

相关问题 更多 >

    热门问题