如何在Q语言(kdb)中获取当前运行文件路径,类似Python的__file__?
__file__) Great question! Unlike Python which has the handy __file__ attribute built-in, Q/kdb+ doesn't offer a direct out-of-the-box equivalent. But don't worry—there are several reliable workarounds to fetch the path of your currently running script. Let's walk through them:
Method 1: Parse .z.s (For Scripts Loaded with \l)
When you load a script using the \l (load) command (e.g., \l my_script.q), the .z.s system variable returns the current execution expression. We can parse this to extract the script path:
// Inside your script file script_path: first " " vs first 1 _ string .z.s
How it works:
.z.swill return a value like`\\l /full/path/to/your/script.q`when the script is loaded.- Converting it to a string, stripping the first character (the backtick), splitting on spaces, and taking the second element gives you the full script path.
Method 2: Use System Process Info (More Reliable, Cross-Platform)
This method leverages system commands to fetch the Q process's command-line arguments, which includes the script path if the script was launched via q script.q or loaded in a way that's part of the process args.
For Linux/macOS:
script_path: first 1 _ " " vs first system "ps -p ", string .z.pid, " -o args="
For Windows:
script_path: first 1 _ " " vs first system "wmic process where processid=", string .z.pid, " get commandline | findstr /v CommandLine"
How it works:
.z.pidgives you the current Q process ID.- We use system commands (
pson Unix-like systems,wmicon Windows) to get the command line that started the process. - Splitting the result and taking the second element skips the
q/q.exeexecutable name, leaving the script path.
Method 3: Wrap It in a Cross-Platform Function
To avoid writing OS-specific code every time, you can create a reusable function that handles both Unix-like and Windows systems:
get_script_path:{ $[ .z.os=`w; // Check if running on Windows first 1 _ " " vs first system "wmic process where processid=", string .z.pid, " get commandline | findstr /v CommandLine"; first 1 _ " " vs first system "ps -p ", string .z.pid, " -o args=" ] }
Just call get_script_path[] anywhere in your script to get the full path.
Important Notes:
- These methods work best when your script is run as a file (either via
q script.qor loaded with\l). In an interactive Q session where you're typing commands directly, they'll return empty or irrelevant values since there's no script file involved. - If your script is loaded from a relative path, the returned path will reflect that—you can use
.z.p(current working directory) to convert it to an absolute path if needed.
内容的提问来源于stack exchange,提问作者user983716

