要获取当前正在执行的文件的路径和名称,可以使用以下方法:
在Python中,可以使用__file__
变量来获取当前正在执行的文件的路径和名称。例如:
import os
current_file_path = os.path.abspath(__file__)
print(current_file_path)
在Node.js中,可以使用__filename
变量来获取当前正在执行的文件的路径和名称。例如:
const path = require('path');
const current_file_path = path.resolve(__filename);
console.log(current_file_path);
在Java中,可以使用System.getProperty("user.dir")
来获取当前正在执行的文件的路径,并使用System.getProperty("user.dir") + File.separator + "filename.txt"
来获取当前正在执行的文件的路径和名称。例如:
import java.io.File;
public class Main {
public static void main(String[] args) {
String current_file_path = System.getProperty("user.dir");
System.out.println(current_file_path);
String current_file_path_and_name = System.getProperty("user.dir") + File.separator + "filename.txt";
System.out.println(current_file_path_and_name);
}
}
在PHP中,可以使用__FILE__
变量来获取当前正在执行的文件的路径和名称。例如:
<?php
$current_file_path = realpath(__FILE__);
echo $current_file_path;
?>
在Ruby中,可以使用__FILE__
变量来获取当前正在执行的文件的路径和名称。例如:
current_file_path = File.expand_path(__FILE__)
puts current_file_path
在Go中,可以使用os.Executable()
函数来获取当前正在执行的文件的路径和名称。例如:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
exe_path, err := os.Executable()
if err != nil {
panic(err)
}
current_file_path, err := filepath.Abs(exe_path)
if err != nil {
panic(err)
}
fmt.Println(current_file_path)
}
在C++中,可以使用argv[0]
变量来获取当前正在执行的文件的路径和名称。例如:
#include<iostream>
#include<string>
#include<filesystem>
int main(int argc, char* argv[]) {
std::filesystem::path current_file_path = std::filesystem::absolute(argv[0]);
std::cout<< current_file_path<< std::endl;
return 0;
}
在C#中,可以使用System.Reflection.Assembly.GetExecutingAssembly().Location
属性来获取当前正在执行的文件的路径和名称。例如:
using System;
using System.IO;
class MainClass {
public static void Main(string[] args) {
string current_file_path = System.Reflection.Assembly.GetExecutingAssembly().Location;
Console.WriteLine(current_file_path);
}
}
在JavaScript中,可以使用__filename
变量来获取当前正在执行的文件的路径和名称。例如:
console.log(__filename);
在Swift中,可以使用#file
变量来获取当前正在执行的文件的路径和名称。例如:
import Foundation
let current_file_path = #file
print(current_file_path)
在Kotlin中,可以使用::class.java.protectionDomain.codeSource.location
属性来获取当前正在执行的文件的路径和名称。例如:
import java.net.URL
fun main() {
val current_file_path = Main::class.java.protectionDomain.codeSource.location.toURI().path
println(current_file_path)
}
在Rust中,可以使用std::env::current_exe()
函数来获取当前正在执行的文件的路径和名称。例如:
use std::env;
fn main() {
let current_file_path = env::current_exe().unwrap();
println!("{:?}", current_file_path);
}
在Scala中,可以使用getClass.getProtectionDomain.getCodeSource.getLocation.getPath
属性来获取当前正在执行的文件的路径和名称。例如:
object Main {
def main(args: Array[String]): Unit = {
val current_file_path = getClass.getProtectionDomain.getCodeSource.getLocation.getPath
println(current_file_path)
}
}
在Perl中,可以使用__FILE__
变量来获取当前正在执行的文件的路径和名称。例如:
print __FILE__;
在Lua中,可以使用arg[0]
变量来获取当前正在执行的文件的路径和名称。例如:
print(arg[0])
在R中,可以使用commandArgs()
函数来获取当前正在�
领取专属 10元无门槛券
手把手带您无忧上云