我想加载一个位于当前工作文件夹子目录中的 lisp 脚本。相对路径是./crossover-operators/ER.lisp.
在 Linux 中,这是通过以下方式完成的:
(load "./crossover-operators/ER.lisp")
在 Windows 中由以下人员完成:
(load ".\\crossover-operators\\ER.lisp")
如何创建一个独立于运行我的 Common Lisp 脚本的操作系统来加载 ER.lisp 脚本的函数?
最佳答案
首先,19.1.1 Namestrings as Filenames说确实,namestring(字符串作为路径名)不可移植。
A conforming program must never unconditionally use a literal namestring other than a logical pathname namestring because Common Lisp does not define any namestring syntax other than that for logical pathnames that would be guaranteed to be portable.
另请注意,如果您向用户询问文件名,您可以方便地使用它们:
However, a conforming program can, if it is careful, successfully manipulate user-supplied data which contains or refers to non-portable namestrings.
您有两个选项,这两个选项并不互斥:使用路径名构造器和/或使用逻辑路径名。
路径名构造函数
使用make-pathname
、merge-pathnames
构建路径名。路径名是具有不同组件(目录、名称、类型等)的结构,可以组合在一起。它们是用 prototypal inheritance 构建的方法,您可以通过复制现有路径并更改其某些组件来创建新路径名。
make-pathname
就像一个 struct 构造函数,除了它有一个 :defaults
参数,它给出了一个用作原型(prototype)的路径名。
merge-pathnames
有点不同,因为它也执行语义操作。
例如,如果保存默认路径名的特殊变量*default-pathname-defaults*
设置如下:
USER> (setf *default-pathname-defaults*
(make-pathname :directory '(:relative "crossover-operator")))
#P"crossover-operator/"
然后你有两种不同的行为。
USER> (make-pathname :directory '(:relative "tmp")
:defaults *default-pathname-defaults*)
#P"tmp/"
make-pathname
替换原始路径名的目录部分。
USER> (merge-pathnames *)
#P"crossover-operator/tmp/"
merge-pathnames
获取一个路径名(这里是我们刚刚构建的那个,用 *
表示),并将目录相对于 * 中的目录合并默认路径名默认值*
。
逻辑路径名
逻辑路径名有点像 URL(统一资源定位符),只是间接代表文件。程序员必须根据地址的 HOST
部分定义从逻辑路径名到实际物理路径名的转换函数。
路径名(名称字符串)的打印表示是不可移植的,除了逻辑路径名。见 19.3.1 Syntax of Logical Pathname Namestrings .
除了具有定义的语法和转换函数(从逻辑路径名到物理路径名)之外,它们的行为与其他路径名相同,因此您可以调用 merge-pathnames
,如上所示。
路径名翻译可以映射到不可移植的名称字符串(但您可以在不同的主机上设置不同的翻译),也可以映射到逻辑或物理路径名。 LOGICAL-PATHNAME-TRANSLATIONS
的超规范有一些关于如何使用逻辑路径名的例子,比如这个:
;;;A more complex example, dividing the files among two file servers
;;;and several different directories. This Unix doesn't support
;;;:WILD-INFERIORS in the directory, so each directory level must
;;;be translated individually. No file name or type translations
;;;are required except for .MAIL to .MBX.
;;;The namestring syntax on the right-hand side is implementation-dependent.
(setf (logical-pathname-translations "prog")
'(("RELEASED;*.*.*" "MY-UNIX:/sys/bin/my-prog/")
("RELEASED;*;*.*.*" "MY-UNIX:/sys/bin/my-prog/*/")
("EXPERIMENTAL;*.*.*" "MY-UNIX:/usr/Joe/development/prog/")
("EXPERIMENTAL;DOCUMENTATION;*.*.*"
"MY-VAX:SYS$DISK:[JOE.DOC]")
("EXPERIMENTAL;*;*.*.*" "MY-UNIX:/usr/Joe/development/prog/*/")
("MAIL;**;*.MAIL" "MY-VAX:SYS$DISK:[JOE.MAIL.PROG...]*.MBX")))
;;;Sample use of that logical pathname. The return value
;;;is implementation-dependent.
(translate-logical-pathname "prog:mail;save;ideas.mail.3")
=> #P"MY-VAX:SYS$DISK:[JOE.MAIL.PROG.SAVE]IDEAS.MBX.3"
关于filesystems - Common Lisp 中独立于操作系统的路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61958853/