OS

Hereda: Object

Proporciona acceso a funcionalidades comunes del sistema operativo.

Descripción

The OS class wraps the most common functionalities for communicating with the host operating system, such as the video driver, delays, environment variables, execution of binaries, command line, etc.

Note: In Godot 4, OS functions related to window management, clipboard, and TTS were moved to the DisplayServer singleton (and the Window class). Functions related to time were removed and are only available in the Time class.

Tutoriales

Propiedades

bool

delta_smoothing

true

bool

low_processor_usage_mode

false

int

low_processor_usage_mode_sleep_usec

6900

Métodos

void

add_logger(logger: Logger)

void

alert(text: String, title: String = "Alert!")

void

close_midi_inputs()

void

crash(message: String)

int

create_instance(arguments: PackedStringArray)

int

create_process(path: String, arguments: PackedStringArray, open_console: bool = false)

void

delay_msec(msec: int) const

void

delay_usec(usec: int) const

int

execute(path: String, arguments: PackedStringArray, output: Array = [], read_stderr: bool = false, open_console: bool = false)

Dictionary

execute_with_pipe(path: String, arguments: PackedStringArray, blocking: bool = true)

Key

find_keycode_from_string(string: String) const

String

get_cache_dir() const

PackedStringArray

get_cmdline_args()

PackedStringArray

get_cmdline_user_args()

String

get_config_dir() const

PackedStringArray

get_connected_midi_inputs()

String

get_data_dir() const

String

get_distribution_name() const

PackedByteArray

get_entropy(size: int)

String

get_environment(variable: String) const

String

get_executable_path() const

PackedStringArray

get_granted_permissions() const

String

get_keycode_string(code: Key) const

String

get_locale() const

String

get_locale_language() const

int

get_main_thread_id() const

Dictionary

get_memory_info() const

String

get_model_name() const

String

get_name() const

int

get_process_exit_code(pid: int) const

int

get_process_id() const

int

get_processor_count() const

String

get_processor_name() const

PackedStringArray

get_restart_on_exit_arguments() const

int

get_static_memory_peak_usage() const

int

get_static_memory_usage() const

StdHandleType

get_stderr_type() const

StdHandleType

get_stdin_type() const

StdHandleType

get_stdout_type() const

String

get_system_ca_certificates()

String

get_system_dir(dir: SystemDir, shared_storage: bool = true) const

String

get_system_font_path(font_name: String, weight: int = 400, stretch: int = 100, italic: bool = false) const

PackedStringArray

get_system_font_path_for_text(font_name: String, text: String, locale: String = "", script: String = "", weight: int = 400, stretch: int = 100, italic: bool = false) const

PackedStringArray

get_system_fonts() const

String

get_temp_dir() const

int

get_thread_caller_id() const

String

get_unique_id() const

String

get_user_data_dir() const

String

get_version() const

String

get_version_alias() const

PackedStringArray

get_video_adapter_driver_info() const

bool

has_environment(variable: String) const

bool

has_feature(tag_name: String) const

bool

is_debug_build() const

bool

is_keycode_unicode(code: int) const

bool

is_process_running(pid: int) const

bool

is_restart_on_exit_set() const

bool

is_sandboxed() const

bool

is_stdout_verbose() const

bool

is_userfs_persistent() const

Error

kill(pid: int)

Error

move_to_trash(path: String) const

void

open_midi_inputs()

Error

open_with_program(program_path: String, paths: PackedStringArray)

PackedByteArray

read_buffer_from_stdin(buffer_size: int = 1024)

String

read_string_from_stdin(buffer_size: int = 1024)

void

remove_logger(logger: Logger)

bool

request_permission(name: String)

bool

request_permissions()

void

revoke_granted_permissions()

void

set_environment(variable: String, value: String) const

void

set_restart_on_exit(restart: bool, arguments: PackedStringArray = PackedStringArray())

Error

set_thread_name(name: String)

void

set_use_file_access_save_and_swap(enabled: bool)

Error

shell_open(uri: String)

Error

shell_show_in_file_manager(file_or_dir_path: String, open_folder: bool = true)

void

unset_environment(variable: String) const


Enumeraciones

enum RenderingDriver: 🔗

RenderingDriver RENDERING_DRIVER_VULKAN = 0

El controlador de renderizado de Vulkan. Requiere soporte para Vulkan 1.0 y utiliza automáticamente las características de Vulkan 1.1 y 1.2 si están disponibles.

RenderingDriver RENDERING_DRIVER_OPENGL3 = 1

The OpenGL 3 rendering driver. It uses OpenGL 3.3 Core Profile on desktop platforms, OpenGL ES 3.0 on mobile devices, and WebGL 2.0 on Web.

RenderingDriver RENDERING_DRIVER_D3D12 = 2

El controlador de renderizado de Direct3D 12.

RenderingDriver RENDERING_DRIVER_METAL = 3

El controlador de renderizado de Metal.


enum SystemDir: 🔗

SystemDir SYSTEM_DIR_DESKTOP = 0

Refers to the Desktop directory path.

SystemDir SYSTEM_DIR_DCIM = 1

Refers to the DCIM (Digital Camera Images) directory path.

SystemDir SYSTEM_DIR_DOCUMENTS = 2

Se refiere a la ruta del directorio de Documentos.

SystemDir SYSTEM_DIR_DOWNLOADS = 3

Se refiere a la ruta del directorio de Descargas.

SystemDir SYSTEM_DIR_MOVIES = 4

Se refiere a la ruta del directorio de Películas (o Videos).

SystemDir SYSTEM_DIR_MUSIC = 5

Se refiere a la ruta del directorio de Música.

SystemDir SYSTEM_DIR_PICTURES = 6

Se refiere a la ruta del directorio de Imágenes.

SystemDir SYSTEM_DIR_RINGTONES = 7

Se refiere a la ruta del directorio de Ringtones.


enum StdHandleType: 🔗

StdHandleType STD_HANDLE_INVALID = 0

El dispositivo de E/S estándar no es válido. No se pueden recibir ni enviar datos a estos dispositivos de E/S estándar.

StdHandleType STD_HANDLE_CONSOLE = 1

El dispositivo de E/S estándar es una consola. Esto suele ocurrir cuando Godot se ejecuta desde una terminal sin redirección. También se utiliza para todos los dispositivos de E/S estándar cuando se ejecuta Godot desde el editor, al menos en las plataformas de escritorio.

StdHandleType STD_HANDLE_FILE = 2

El dispositivo de E/S estándar es un archivo normal. Esto suele ocurrir con la redirección desde una terminal, por ejemplo, godot > stdout.txt, godot < stdin.txt o godot > stdout_stderr.txt 2>&1.

StdHandleType STD_HANDLE_PIPE = 3

El dispositivo de E/S estándar es una FIFO/pipe. Esto suele ocurrir con el uso de pipes desde una terminal, por ejemplo, echo "Hello" | godot.

StdHandleType STD_HANDLE_UNKNOWN = 4

El tipo de dispositivo de E/S estándar es desconocido.


Descripciones de Propiedades

bool delta_smoothing = true 🔗

  • void set_delta_smoothing(value: bool)

  • bool is_delta_smoothing_enabled()

Si es true, el motor filtra el tiempo delta medido entre cada fotograma e intenta compensar la variación aleatoria. Esto sólo funciona en sistemas donde V-Sync está activo.

Nota: Al iniciar, esto es lo mismo que ProjectSettings.application/run/delta_smoothing.


bool low_processor_usage_mode = false 🔗

  • void set_low_processor_usage_mode(value: bool)

  • bool is_in_low_processor_usage_mode()

Si es true, el motor se optimiza para un bajo uso del procesador, sólo refrescando la pantalla si es necesario. Puede mejorar el consumo de la batería en el móvil.

Nota: Al iniciar, esto es lo mismo que ProjectSettings.application/run/low_processor_mode.


int low_processor_usage_mode_sleep_usec = 6900 🔗

  • void set_low_processor_usage_mode_sleep_usec(value: int)

  • int get_low_processor_usage_mode_sleep_usec()

La cantidad de tiempo que se duerme entre fotogramas cuando el modo de bajo uso del procesador está activado, en microsegundos. Los valores más altos resultarán en un menor uso de la CPU. Véase también low_processor_usage_mode.

Nota: Al iniciar, esto es lo mismo que ProjectSettings.application/run/low_processor_mode_sleep_usec.


Descripciones de Métodos

void add_logger(logger: Logger) 🔗

Add a custom logger to intercept the internal message stream.


void alert(text: String, title: String = "Alert!") 🔗

Displays a modal dialog box using the host platform's implementation. The engine execution is blocked until the dialog is closed.


void close_midi_inputs() 🔗

Shuts down the system MIDI driver. Godot will no longer receive InputEventMIDI. See also open_midi_inputs() and get_connected_midi_inputs().

Note: This method is implemented on Linux, macOS, Windows, and Web.


void crash(message: String) 🔗

Crashes the engine (or the editor if called within a @tool script). See also kill().

Note: This method should only be used for testing the system's crash handler, not for any other purpose. For general error reporting, use (in order of preference) @GDScript.assert(), @GlobalScope.push_error(), or alert().


int create_instance(arguments: PackedStringArray) 🔗

Creates a new instance of Godot that runs independently. The arguments are used in the given order and separated by a space.

If the process is successfully created, this method returns the new process' ID, which you can use to monitor the process (and potentially terminate it with kill()). If the process cannot be created, this method returns -1.

See create_process() if you wish to run a different process.

Note: This method is implemented on Android, Linux, macOS and Windows.


int create_process(path: String, arguments: PackedStringArray, open_console: bool = false) 🔗

Creates a new process that runs independently of Godot. It will not terminate when Godot terminates. The path specified in path must exist and be an executable file or macOS .app bundle. The path is resolved based on the current platform. The arguments are used in the given order and separated by a space.

On Windows, if open_console is true and the process is a console app, a new terminal window will be opened.

If the process is successfully created, this method returns its process ID, which you can use to monitor the process (and potentially terminate it with kill()). Otherwise, this method returns -1.

Example: Run another instance of the project:

var pid = OS.create_process(OS.get_executable_path(), [])

See execute() if you wish to run an external command and retrieve the results.

Note: This method is implemented on Android, Linux, macOS, and Windows.

Note: On macOS, sandboxed applications are limited to run only embedded helper executables, specified during export or system .app bundle, system .app bundles will ignore arguments.


void delay_msec(msec: int) const 🔗

Delays execution of the current thread by msec milliseconds. msec must be greater than or equal to 0. Otherwise, delay_msec() does nothing and prints an error message.

Note: delay_msec() is a blocking way to delay code execution. To delay code execution in a non-blocking way, you may use SceneTree.create_timer(). Awaiting with SceneTreeTimer delays the execution of code placed below the await without affecting the rest of the project (or editor, for EditorPlugins and EditorScripts).

Note: When delay_msec() is called on the main thread, it will freeze the project and will prevent it from redrawing and registering input until the delay has passed. When using delay_msec() as part of an EditorPlugin or EditorScript, it will freeze the editor but won't freeze the project if it is currently running (since the project is an independent child process).


void delay_usec(usec: int) const 🔗

Delays execution of the current thread by usec microseconds. usec must be greater than or equal to 0. Otherwise, delay_usec() does nothing and prints an error message.

Note: delay_usec() is a blocking way to delay code execution. To delay code execution in a non-blocking way, you may use SceneTree.create_timer(). Awaiting with a SceneTreeTimer delays the execution of code placed below the await without affecting the rest of the project (or editor, for EditorPlugins and EditorScripts).

Note: When delay_usec() is called on the main thread, it will freeze the project and will prevent it from redrawing and registering input until the delay has passed. When using delay_usec() as part of an EditorPlugin or EditorScript, it will freeze the editor but won't freeze the project if it is currently running (since the project is an independent child process).


int execute(path: String, arguments: PackedStringArray, output: Array = [], read_stderr: bool = false, open_console: bool = false) 🔗

Executes the given process in a blocking way. The file specified in path must exist and be executable. The system path resolution will be used. The arguments are used in the given order, separated by spaces, and wrapped in quotes.

If an output array is provided, the complete shell output of the process is appended to output as a single String element. If read_stderr is true, the output to the standard error stream is also appended to the array.

On Windows, if open_console is true and the process is a console app, a new terminal window is opened.

This method returns the exit code of the command, or -1 if the process fails to execute.

Note: The main thread will be blocked until the executed command terminates. Use Thread to create a separate thread that will not block the main thread, or use create_process() to create a completely independent process.

For example, to retrieve a list of the working directory's contents:

var output = []
var exit_code = OS.execute("ls", ["-l", "/tmp"], output)

If you wish to access a shell built-in or execute a composite command, a platform-specific shell can be invoked. For example:

var output = []
OS.execute("CMD.exe", ["/C", "cd %TEMP% && dir"], output)

Note: This method is implemented on Android, Linux, macOS, and Windows.

Note: To execute a Windows command interpreter built-in command, specify cmd.exe in path, /c as the first argument, and the desired command as the second argument.

Note: To execute a PowerShell built-in command, specify powershell.exe in path, -Command as the first argument, and the desired command as the second argument.

Note: To execute a Unix shell built-in command, specify shell executable name in path, -c as the first argument, and the desired command as the second argument.

Note: On macOS, sandboxed applications are limited to run only embedded helper executables, specified during export.

Note: On Android, system commands such as dumpsys can only be run on a rooted device.


Dictionary execute_with_pipe(path: String, arguments: PackedStringArray, blocking: bool = true) 🔗

Creates a new process that runs independently of Godot with redirected IO. It will not terminate when Godot terminates. The path specified in path must exist and be an executable file or macOS .app bundle. The path is resolved based on the current platform. The arguments are used in the given order and separated by a space.

If blocking is false, created pipes work in non-blocking mode, i.e. read and write operations will return immediately. Use FileAccess.get_error() to check if the last read/write operation was successful.

If the process cannot be created, this method returns an empty Dictionary. Otherwise, this method returns a Dictionary with the following keys:

  • "stdio" - FileAccess to access the process stdin and stdout pipes (read/write).

  • "stderr" - FileAccess to access the process stderr pipe (read only).

  • "pid" - Process ID as an int, which you can use to monitor the process (and potentially terminate it with kill()).

Note: This method is implemented on Android, Linux, macOS, and Windows.

Note: To execute a Windows command interpreter built-in command, specify cmd.exe in path, /c as the first argument, and the desired command as the second argument.

Note: To execute a PowerShell built-in command, specify powershell.exe in path, -Command as the first argument, and the desired command as the second argument.

Note: To execute a Unix shell built-in command, specify shell executable name in path, -c as the first argument, and the desired command as the second argument.

Note: On macOS, sandboxed applications are limited to run only embedded helper executables, specified during export or system .app bundle, system .app bundles will ignore arguments.


Key find_keycode_from_string(string: String) const 🔗

Finds the keycode for the given string. The returned values are equivalent to the Key constants.

print(OS.find_keycode_from_string("C"))         # Prints 67 (KEY_C)
print(OS.find_keycode_from_string("Escape"))    # Prints 4194305 (KEY_ESCAPE)
print(OS.find_keycode_from_string("Shift+Tab")) # Prints 37748738 (KEY_MASK_SHIFT | KEY_TAB)
print(OS.find_keycode_from_string("Unknown"))   # Prints 0 (KEY_NONE)

See also get_keycode_string().


String get_cache_dir() const 🔗

Returns the global cache data directory according to the operating system's standards.

On the Linux/BSD platform, this path can be overridden by setting the XDG_CACHE_HOME environment variable before starting the project. See File paths in Godot projects in the documentation for more information. See also get_config_dir() and get_data_dir().

Not to be confused with get_user_data_dir(), which returns the project-specific user data path.


PackedStringArray get_cmdline_args() 🔗

Returns the command-line arguments passed to the engine, excluding arguments processed by the engine, such as --headless and --fullscreen.

# Godot has been executed with the following command:
# godot --headless --verbose --scene my_scene.tscn --custom
OS.get_cmdline_args() # Returns ["--scene", "my_scene.tscn", "--custom"]

Command-line arguments can be written in any form, including both --key value and --key=value forms so they can be properly parsed, as long as custom command-line arguments do not conflict with engine arguments.

You can also incorporate environment variables using the get_environment() method.

You can set ProjectSettings.editor/run/main_run_args to define command-line arguments to be passed by the editor when running the project.

Example: Parse command-line arguments into a Dictionary using the --key=value form for arguments:

var arguments = {}
for argument in OS.get_cmdline_args():
    if argument.contains("="):
        var key_value = argument.split("=")
        arguments[key_value[0].trim_prefix("--")] = key_value[1]
    else:
        # Options without an argument will be present in the dictionary,
        # with the value set to an empty string.
        arguments[argument.trim_prefix("--")] = ""

Note: Passing custom user arguments directly is not recommended, as the engine may discard or modify them. Instead, pass the standard UNIX double dash (--) and then the custom arguments, which the engine will ignore by design. These can be read via get_cmdline_user_args().


PackedStringArray get_cmdline_user_args() 🔗

Returns the command-line user arguments passed to the engine. User arguments are ignored by the engine and reserved for the user. They are passed after the double dash -- argument. ++ may be used when -- is intercepted by another program (such as startx).

# Godot has been executed with the following command:
# godot --fullscreen --custom -- --level=2 --hardcore

OS.get_cmdline_args()      # Returns ["--custom"]
OS.get_cmdline_user_args() # Returns ["--level=2", "--hardcore"]

To get arguments passed before -- or ++, use get_cmdline_args().


String get_config_dir() const 🔗

Returns the global user configuration directory according to the operating system's standards.

On the Linux/BSD platform, this path can be overridden by setting the XDG_CONFIG_HOME environment variable before starting the project. See File paths in Godot projects in the documentation for more information. See also get_cache_dir() and get_data_dir().

Not to be confused with get_user_data_dir(), which returns the project-specific user data path.


PackedStringArray get_connected_midi_inputs() 🔗

Devuelve un array de nombres de dispositivos MIDI conectados, si existen. Devuelve un array vacío si el driver MIDI del sistema no ha sido inicializado previamente con open_midi_inputs(). Véase también close_midi_inputs().

Nota: Este método está implementado en Linux, macOS, Windows y Web.

Nota: En la plataforma Web, Web MIDI necesita ser soportado por el navegador. Por el momento, es actualmente soportado por todos los navegadores principales, excepto Safari.

Nota: En la plataforma Web, usar la entrada MIDI requiere que un permiso del navegador sea concedido primero. Esta petición de permiso se realiza al llamar a open_midi_inputs(). El navegador se abstendrá de procesar la entrada MIDI hasta que el usuario acepte la petición de permiso.


String get_data_dir() const 🔗

Devuelve el directorio de datos de usuario global de acuerdo con los estándares del sistema operativo.

En la plataforma Linux/BSD, esta ruta puede ser sobreescrita estableciendo la variable de entorno XDG_DATA_HOME antes de iniciar el proyecto. Véase Rutas de archivos en proyectos de Godot en la documentación para más información. Véase también get_cache_dir() y get_config_dir().

No debe confundirse con get_user_data_dir(), que devuelve la ruta de datos de usuario específica del proyecto.


String get_distribution_name() const 🔗

Devuelve el nombre de la distribución para plataformas Linux y BSD (p. ej., "Ubuntu", "Manjaro", "OpenBSD", etc.).

Devuelve el mismo valor que get_name() para ROMs de Android de fábrica, pero intenta devolver el nombre de la ROM personalizada para derivados populares de Android como "LineageOS".

Devuelve el mismo valor que get_name() para otras plataformas.

Nota: Este método no es compatible con la plataforma Web. Devuelve una string vacía.


PackedByteArray get_entropy(size: int) 🔗

Genera un PackedByteArray de bytes aleatorios criptográficamente seguros con el size dado.

Nota: Generar grandes cantidades de bytes usando este método puede resultar en bloqueo y entropía de menor calidad en la mayoría de las plataformas. Es preferible usar Crypto.generate_random_bytes() en la mayoría de los casos.


String get_environment(variable: String) const 🔗

Devuelve el valor de la variable de entorno dada, o una string vacía si variable no existe.

Nota: Comprueba bien las mayúsculas y minúsculas de variable. Los nombres de las variables de entorno distinguen entre mayúsculas y minúsculas en todas las plataformas excepto Windows.

Nota: En macOS, las aplicaciones no tienen acceso a las variables de entorno del shell.


String get_executable_path() const 🔗

Devuelve la ruta del archivo ejecutable del motor actual.

Nota: En macOS, si quieres iniciar otra instancia de Godot, usa siempre create_instance() en lugar de depender de la ruta del ejecutable.


PackedStringArray get_granted_permissions() const 🔗

En dispositivos Android: Devuelve la lista de permisos peligrosos que se han concedido.

En macOS: Devuelve la lista de permisos concedidos y las carpetas seleccionadas por el usuario a las que puede acceder la aplicación (solo aplicaciones en sandbox). Usa el diálogo de archivos nativo para solicitar permiso de acceso a la carpeta.

En iOS, visionOS: Devuelve la lista de permisos concedidos.


String get_keycode_string(code: Key) const 🔗

Returns the given keycode as a String.

print(OS.get_keycode_string(KEY_C))                    # Prints "C"
print(OS.get_keycode_string(KEY_ESCAPE))               # Prints "Escape"
print(OS.get_keycode_string(KEY_MASK_SHIFT | KEY_TAB)) # Prints "Shift+Tab"

See also find_keycode_from_string(), InputEventKey.keycode, and InputEventKey.get_keycode_with_modifiers().


String get_locale() const 🔗

Returns the host OS locale as a String of the form language_Script_COUNTRY_VARIANT@extra. Every substring after language is optional and may not exist.

  • language - 2 or 3-letter language code, in lower case.

  • Script - 4-letter script code, in title case.

  • COUNTRY - 2 or 3-letter country code, in upper case.

  • VARIANT - language variant, region and sort order. The variant can have any number of underscored keywords.

  • extra - semicolon separated list of additional key words. This may include currency, calendar, sort order and numbering system information.

If you want only the language code and not the fully specified locale from the OS, you can use get_locale_language().


String get_locale_language() const 🔗

Returns the host OS locale's 2 or 3-letter language code as a string which should be consistent on all platforms. This is equivalent to extracting the language part of the get_locale() string.

This can be used to narrow down fully specified locale strings to only the "common" language code, when you don't need the additional information about country code or variants. For example, for a French Canadian user with fr_CA locale, this would return fr.


int get_main_thread_id() const 🔗

Devuelve el ID del hilo principal. Véase get_thread_caller_id().

Nota: Los ID de los hilos no son deterministas y pueden ser reutilizados al reiniciar la aplicación.


Dictionary get_memory_info() const 🔗

Devuelve un Dictionary que contiene información sobre la memoria actual con las siguientes entradas:

  • "physical" - cantidad total de memoria física utilizable en bytes. Este valor puede ser ligeramente inferior a la cantidad real de memoria física, ya que no incluye la memoria reservada por el kernel y los dispositivos.

  • "free" - cantidad de memoria física que se puede asignar inmediatamente sin acceso al disco u otras operaciones costosas, en bytes. El proceso podría asignar más memoria física, pero esta acción requerirá el traslado de las páginas inactivas al disco, lo que puede ser costoso.

  • "available" - cantidad de memoria que se puede asignar sin extender los archivos de intercambio (swap), en bytes. Este valor incluye tanto la memoria física como el swap.

  • "stack" - tamaño de la pila (stack) del hilo actual en bytes.

Nota: El valor de cada entrada puede ser -1 si se desconoce.


String get_model_name() const 🔗

Devuelve el nombre del modelo del dispositivo actual.

Nota: Este método está implementado en Android, iOS, macOS y Windows. Devuelve "GenericDevice" en plataformas no compatibles.


String get_name() const 🔗

Returns the name of the host platform.

  • On Windows, this is "Windows".

  • On macOS, this is "macOS".

  • On Linux-based operating systems, this is "Linux".

  • On BSD-based operating systems, this is "FreeBSD", "NetBSD", "OpenBSD", or "BSD" as a fallback.

  • On Android, this is "Android".

  • On iOS, this is "iOS".

  • On Web, this is "Web".

Note: Custom builds of the engine may support additional platforms, such as consoles, possibly returning other names.

match OS.get_name():
    "Windows":
        print("Welcome to Windows!")
    "macOS":
        print("Welcome to macOS!")
    "Linux", "FreeBSD", "NetBSD", "OpenBSD", "BSD":
        print("Welcome to Linux/BSD!")
    "Android":
        print("Welcome to Android!")
    "iOS":
        print("Welcome to iOS!")
    "Web":
        print("Welcome to the Web!")

Note: On Web platforms, it is still possible to determine the host platform's OS with feature tags. See has_feature().


int get_process_exit_code(pid: int) const 🔗

Devuelve el código de salida de un proceso generado una vez que ha terminado de ejecutarse (véase is_process_running()).

Devuelve -1 si el pid no es un PID de un proceso hijo generado, el proceso aún se está ejecutando o el método no está implementado para la plataforma actual.

Nota: Devuelve -1 si el pid es un proceso de aplicación agrupada de macOS.

Nota: Este método está implementado en Android, Linux, macOS y Windows.


int get_process_id() const 🔗

Devuelve el número utilizado por la máquina host para identificar de forma única esta aplicación.

Nota: En Web, este método siempre devuelve 0.


int get_processor_count() const 🔗

Devuelve el número de núcleos de CPU lógicos disponibles en la máquina host. En las CPU con HyperThreading habilitado, este número será mayor que el número de núcleos de CPU físicos.


String get_processor_name() const 🔗

Devuelve el nombre completo del modelo de CPU en la máquina host (p. ej. "Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz").

Nota: Este método sólo está implementado en Windows, macOS, Linux e iOS. En Android y Web, get_processor_name() devuelve una string vacía.


PackedStringArray get_restart_on_exit_arguments() const 🔗

Devuelve la lista de argumentos de la línea de comandos que se utilizarán cuando el proyecto se reinicie automáticamente utilizando set_restart_on_exit(). Véase también is_restart_on_exit_set().


int get_static_memory_peak_usage() const 🔗

Devuelve la cantidad máxima de memoria estática utilizada. Solo funciona en las compilaciones de depuración.


int get_static_memory_usage() const 🔗

Devuelve la cantidad de memoria estática que está utilizando el programa en bytes. Solo funciona en las compilaciones de depuración.


StdHandleType get_stderr_type() const 🔗

Devuelve el tipo del dispositivo de error estándar.

Nota: Este método está implementado en Linux, macOS y Windows.


StdHandleType get_stdin_type() const 🔗

Devuelve el tipo del dispositivo de entrada estándar.

Nota: Este método está implementado en Linux, macOS y Windows.

Nota: En las compilaciones exportadas de Windows, ejecuta el ejecutable del contenedor de la consola para acceder a la entrada estándar. Si necesitas un único ejecutable con soporte completo para la consola, utiliza una compilación personalizada compilada con la bandera windows_subsystem=console.


StdHandleType get_stdout_type() const 🔗

Devuelve el tipo del dispositivo de salida estándar.

Nota: Este método está implementado en Linux, macOS y Windows.


String get_system_ca_certificates() 🔗

Devuelve la lista de autoridades de certificación en las que confía el sistema operativo como una string de certificados concatenados en formato PEM.


String get_system_dir(dir: SystemDir, shared_storage: bool = true) const 🔗

Devuelve la ruta a las carpetas de uso común en diferentes plataformas, tal como se define en dir. Consulta las constantes de SystemDir para ver las ubicaciones disponibles.

Nota: Este método está implementado en Android, Linux, macOS y Windows.

Nota: El almacenamiento compartido está implementado en Android y permite diferenciar entre los directorios específicos de la aplicación y los directorios compartidos, si shared_storage es true. Los directorios compartidos tienen restricciones adicionales en Android.


String get_system_font_path(font_name: String, weight: int = 400, stretch: int = 100, italic: bool = false) const 🔗

Returns the path to the system font file with font_name and style. Returns an empty string if no matching fonts found.

The following aliases can be used to request default fonts: "sans-serif", "serif", "monospace", "cursive", and "fantasy".

Note: Returned font might have different style if the requested style is not available.

Note: This method is implemented on Android, iOS, Linux, macOS and Windows.


PackedStringArray get_system_font_path_for_text(font_name: String, text: String, locale: String = "", script: String = "", weight: int = 400, stretch: int = 100, italic: bool = false) const 🔗

Returns an array of the system substitute font file paths, which are similar to the font with font_name and style for the specified text, locale, and script. Returns an empty array if no matching fonts found.

The following aliases can be used to request default fonts: "sans-serif", "serif", "monospace", "cursive", and "fantasy".

Note: Depending on OS, it's not guaranteed that any of the returned fonts will be suitable for rendering specified text. Fonts should be loaded and checked in the order they are returned, and the first suitable one used.

Note: Returned fonts might have different style if the requested style is not available or belong to a different font family.

Note: This method is implemented on Android, iOS, Linux, macOS and Windows.


PackedStringArray get_system_fonts() const 🔗

Returns the list of font family names available.

Note: This method is implemented on Android, iOS, Linux, macOS and Windows.


String get_temp_dir() const 🔗

Returns the global temporary data directory according to the operating system's standards.


int get_thread_caller_id() const 🔗

Returns the ID of the current thread. This can be used in logs to ease debugging of multi-threaded applications.

Note: Thread IDs are not deterministic and may be reused across application restarts.


String get_unique_id() const 🔗

Returns a string that is unique to the device.

Note: This string may change without notice if the user reinstalls their operating system, upgrades it, or modifies their hardware. This means it should generally not be used to encrypt persistent data, as the data saved before an unexpected ID change would become inaccessible. The returned string may also be falsified using external programs, so do not rely on the string returned by this method for security purposes.

Note: On Web, returns an empty string and generates an error, as this method cannot be implemented for security reasons.


String get_user_data_dir() const 🔗

Returns the absolute directory path where user data is written (the user:// directory in Godot). The path depends on the project name and ProjectSettings.application/config/use_custom_user_dir.

  • On Windows, this is %AppData%\Godot\app_userdata\[project_name], or %AppData%\[custom_name] if use_custom_user_dir is set. %AppData% expands to %UserProfile%\AppData\Roaming.

  • On macOS, this is ~/Library/Application Support/Godot/app_userdata/[project_name], or ~/Library/Application Support/[custom_name] if use_custom_user_dir is set.

  • On Linux and BSD, this is ~/.local/share/godot/app_userdata/[project_name], or ~/.local/share/[custom_name] if use_custom_user_dir is set.

  • On Android and iOS, this is a sandboxed directory in either internal or external storage, depending on the user's configuration.

  • On Web, this is a virtual directory managed by the browser.

If the project name is empty, [project_name] falls back to [unnamed project].

Not to be confused with get_data_dir(), which returns the global (non-project-specific) user home directory.


String get_version() const 🔗

Returns the exact production and build version of the operating system. This is different from the branded version used in marketing. This helps to distinguish between different releases of operating systems, including minor versions, and insider and custom builds.

  • For Windows, the major and minor version are returned, as well as the build number. For example, the returned string may look like 10.0.9926 for a build of Windows 10.

  • For rolling distributions, such as Arch Linux, an empty string is returned.

  • For macOS and iOS, the major and minor version are returned, as well as the patch number.

  • For Android, the SDK version and the incremental build number are returned. If it's a custom ROM, it attempts to return its version instead.

Note: This method is not supported on the Web platform. It returns an empty string.


String get_version_alias() const 🔗

Returns the branded version used in marketing, followed by the build number (on Windows), the version number (on macOS), or the SDK version and incremental build number (on Android). Examples include 11 (build 22000), Sequoia (15.0.0), and 15 (SDK 35 build abc528-11988f).

This value can then be appended to get_name() to get a full, human-readable operating system name and version combination for the operating system. Windows feature updates such as 24H2 are not contained in the resulting string, but Windows Server is recognized as such (e.g. 2025 (build 26100) for Windows Server 2025).

Note: This method is only supported on Windows, macOS, and Android. On other operating systems, it returns the same value as get_version().


PackedStringArray get_video_adapter_driver_info() const 🔗

Returns the video adapter driver name and version for the user's currently active graphics card, as a PackedStringArray. See also RenderingServer.get_video_adapter_api_version().

The first element holds the driver name, such as nvidia, amdgpu, etc.

The second element holds the driver version. For example, on the nvidia driver on a Linux/BSD platform, the version is in the format 510.85.02. For Windows, the driver's format is 31.0.15.1659.

Note: This method is only supported on Linux/BSD and Windows when not running in headless mode. On other platforms, it returns an empty array.

Note: This method will run slowly the first time it is called in a session; it can take several seconds depending on the operating system and hardware. It is blocking if called on the main thread, so it's recommended to call it on a separate thread using Thread. This allows the engine to keep running while the information is being retrieved. However, get_video_adapter_driver_info() is not thread-safe, so it should not be called from multiple threads at the same time.

var thread = Thread.new()

func _ready():
    thread.start(
        func():
            var driver_info = OS.get_video_adapter_driver_info()
            if not driver_info.is_empty():
                print("Driver: %s %s" % [driver_info[0], driver_info[1]])
            else:
                print("Driver: (unknown)")
    )

func _exit_tree():
    thread.wait_to_finish()

bool has_environment(variable: String) const 🔗

Returns true if the environment variable with the name variable exists.

Note: Double-check the casing of variable. Environment variable names are case-sensitive on all platforms except Windows.


bool has_feature(tag_name: String) const 🔗

Devuelve true si la característica para la etiqueta de la característica dada está soportada en la instancia que se está ejecutando actualmente, dependiendo de la plataforma, la construcción, etc. Se puede usar para comprobar si estás ejecutando una compilación de depuración, en una determinada plataforma o arquitectura, etc. Consulta la documentación Etiquetas de características para obtener más detalles.

Nota: Los nombres de las etiquetas distinguen entre mayúsculas y minúsculas.

Nota: En la plataforma Web, se define una de las siguientes etiquetas adicionales para indicar la plataforma host: web_android, web_ios, web_linuxbsd, web_macos o web_windows.


bool is_debug_build() const 🔗

Devuelve true si el binario de Godot utilizado para ejecutar el proyecto es una plantilla de exportación de depuración, o cuando se ejecuta en el editor.

Devuelve false si el binario de Godot utilizado para ejecutar el proyecto es una plantilla de exportación de lanzamiento.

Nota: Para comprobar si el binario de Godot utilizado para ejecutar el proyecto es una plantilla de exportación (depuración o lanzamiento), usa en su lugar OS.has_feature("template").


bool is_keycode_unicode(code: int) const 🔗

Devuelve true si el código de tecla de entrada corresponde a un carácter Unicode. Para obtener una lista de códigos, consulta las constantes de Key.

print(OS.is_keycode_unicode(KEY_G))      # Imprime true
print(OS.is_keycode_unicode(KEY_KP_4))   # Imprime true
print(OS.is_keycode_unicode(KEY_TAB))    # Imprime false
print(OS.is_keycode_unicode(KEY_ESCAPE)) # Imprime false

bool is_process_running(pid: int) const 🔗

Returns true if the child process ID (pid) is still running or false if it has terminated. pid must be a valid ID generated from create_process().

Note: This method is implemented on Android, iOS, Linux, macOS, and Windows.


bool is_restart_on_exit_set() const 🔗

Devuelve true si el proyecto se reiniciará automáticamente cuando salga por cualquier razón, false en caso contrario. Véase también set_restart_on_exit() y get_restart_on_exit_arguments().


bool is_sandboxed() const 🔗

Devuelve true si la aplicación se está ejecutando en el sandbox.

Nota: Este método solo está implementado en macOS y Linux.


bool is_stdout_verbose() const 🔗

Devuelve true si el motor se ejecutó con el argumento de línea de comandos --verbose o -v, o si ProjectSettings.debug/settings/stdout/verbose_stdout es true. Véase también @GlobalScope.print_verbose().


bool is_userfs_persistent() const 🔗

Devuelve true si el sistema de archivos user:// es persistente, es decir, su estado es el mismo después de que un jugador sale y vuelve a iniciar el juego. Relevante para la plataforma Web, donde esta persistencia puede no estar disponible.


Error kill(pid: int) 🔗

Mata (termina) el proceso identificado por el ID de proceso dado (pid), como el ID devuelto por execute() en modo no bloqueante. Véase también crash().

Nota: Este método también se puede utilizar para matar procesos que no fueron generados por el motor.

Nota: Este método está implementado en Android, iOS, Linux, macOS y Windows.


Error move_to_trash(path: String) const 🔗

Mueve el archivo o directorio en la ruta path dada a la papelera de reciclaje del sistema. Véase también DirAccess.remove().

El método solo acepta rutas globales, por lo que es posible que tengas que utilizar ProjectSettings.globalize_path(). No lo uses para archivos en res://, ya que no funcionará en proyectos exportados.

Devuelve @GlobalScope.FAILED si no se encuentra el archivo o el directorio, o si el sistema no admite este método.

var archivo_a_eliminar = "user://slot1.save"
OS.move_to_trash(ProjectSettings.globalize_path(archivo_a_eliminar))

Nota: Este método está implementado en Android, Linux, macOS y Windows.

Nota: Si el usuario ha desactivado la papelera de reciclaje en su sistema, el archivo se eliminará permanentemente.


void open_midi_inputs() 🔗

Inicializa el singleton para el controlador MIDI del sistema, permitiendo que Godot reciba InputEventMIDI. Véase también get_connected_midi_inputs() y close_midi_inputs().

Nota: Este método está implementado en Linux, macOS, Windows y Web.

Nota: En la plataforma Web, Web MIDI necesita ser soportado por el navegador. Por el momento, es actualmente soportado por todos los principales navegadores, excepto Safari.

Nota: En la plataforma Web, el uso de la entrada MIDI requiere que se conceda primero un permiso del navegador. Esta solicitud de permiso se realiza al llamar a open_midi_inputs(). El navegador se abstendrá de procesar la entrada MIDI hasta que el usuario acepte la solicitud de permiso.


Error open_with_program(program_path: String, paths: PackedStringArray) 🔗

Abre uno o más archivos/directorios con la aplicación especificada. El program_path especifica la ruta a la aplicación a utilizar para abrir los archivos, y paths contiene un array de rutas de archivos/directorios a abrir.

Nota: Este método es sobre todo relevante para macOS, donde la apertura de archivos usando create_process() podría fallar. En otras plataformas, esto recurre al uso de create_process().

Nota: En macOS, program_path idealmente debería ser la ruta a un paquete .app.


PackedByteArray read_buffer_from_stdin(buffer_size: int = 1024) 🔗

Reads a user input as raw data from the standard input. This operation can be blocking, which causes the window to freeze if read_buffer_from_stdin() is called on the main thread.

  • If standard input is console, this method will block until the program receives a line break in standard input (usually by the user pressing Enter).

  • If standard input is pipe, this method will block until a specific amount of data is read or pipe is closed.

  • If standard input is a file, this method will read a specific amount of data (or less if end-of-file is reached) and return immediately.

Note: This method is implemented on Linux, macOS, and Windows.

Note: On exported Windows builds, run the console wrapper executable to access the terminal. If standard input is console, calling this method without console wrapped will freeze permanently. If standard input is pipe or file, it can be used without console wrapper. If you need a single executable with full console support, use a custom build compiled with the windows_subsystem=console flag.


String read_string_from_stdin(buffer_size: int = 1024) 🔗

Reads a user input as a UTF-8 encoded string from the standard input. This operation can be blocking, which causes the window to freeze if read_string_from_stdin() is called on the main thread.

  • If standard input is console, this method will block until the program receives a line break in standard input (usually by the user pressing Enter).

  • If standard input is pipe, this method will block until a specific amount of data is read or pipe is closed.

  • If standard input is a file, this method will read a specific amount of data (or less if end-of-file is reached) and return immediately.

Note: This method automatically replaces \r\n line breaks with \n and removes them from the end of the string. Use read_buffer_from_stdin() to read the unprocessed data.

Note: This method is implemented on Linux, macOS, and Windows.

Note: On exported Windows builds, run the console wrapper executable to access the terminal. If standard input is console, calling this method without console wrapped will freeze permanently. If standard input is pipe or file, it can be used without console wrapper. If you need a single executable with full console support, use a custom build compiled with the windows_subsystem=console flag.


void remove_logger(logger: Logger) 🔗

Elimina un logger personalizado añadido por add_logger().


bool request_permission(name: String) 🔗

Solicita permiso al sistema operativo para el name dado. Devuelve true si el permiso ya ha sido concedido. Véase también MainLoop.on_request_permissions_result.

El name debe ser el nombre completo del permiso. Por ejemplo:

  • OS.request_permission("android.permission.READ_EXTERNAL_STORAGE")

  • OS.request_permission("android.permission.POST_NOTIFICATIONS")

  • OS.request_permission("macos.permission.RECORD_SCREEN")

  • OS.request_permission("appleembedded.permission.AUDIO_RECORD")

Nota: En Android, el permiso debe ser comprobado durante la exportación.

Nota: Este método está implementado en las plataformas Android, macOS y visionOS.


bool request_permissions() 🔗

Solicita permisos peligrosos al sistema operativo. Devuelve true si los permisos ya han sido concedidos. Véase también MainLoop.on_request_permissions_result.

Nota: Los permisos deben ser comprobados durante la exportación.

Nota: Este método solo está implementado en Android. Los permisos normales se conceden automáticamente en el momento de la instalación en las aplicaciones de Android.


void revoke_granted_permissions() 🔗

En macOS (solo aplicaciones en sandbox), esta función borra la lista de carpetas seleccionadas por el usuario accesibles a la aplicación.


void set_environment(variable: String, value: String) const 🔗

Establece el valor de la variable de entorno variable a value. La variable de entorno se establecerá para el proceso de Godot y cualquier proceso ejecutado con execute() después de ejecutar set_environment(). La variable de entorno no persistirá en los procesos que se ejecuten después de que finalice el proceso de Godot.

Nota: Los nombres de las variables de entorno distinguen entre mayúsculas y minúsculas en todas las plataformas, excepto en Windows. El nombre de variable no puede estar vacío ni incluir el carácter =. En Windows, existe un límite de 32767 caracteres para la longitud combinada de variable, value y los caracteres = y nulo que se registrarán en el bloque de entorno.


void set_restart_on_exit(restart: bool, arguments: PackedStringArray = PackedStringArray()) 🔗

Si restart es true, reinicia el proyecto automáticamente cuando se sale con SceneTree.quit() o Node.NOTIFICATION_WM_CLOSE_REQUEST. Se pueden proporcionar arguments de la línea de comandos. Para reiniciar el proyecto con los mismos argumentos de la línea de comandos que se utilizaron originalmente para ejecutar el proyecto, pasa get_cmdline_args() como valor para arguments.

Este método se puede utilizar para aplicar cambios de configuración que requieran un reinicio. Véase también is_restart_on_exit_set() y get_restart_on_exit_arguments().

Nota: Este método solo es efectivo en plataformas de escritorio, y solo cuando el proyecto no se inicia desde el editor. No tendrá ningún efecto en las plataformas móviles y web, o cuando el proyecto se inicia desde el editor.

Nota: Si el proceso del proyecto falla o es matado por el usuario (enviando SIGKILL en lugar del SIGTERM habitual), el proyecto no se reiniciará automáticamente.


Error set_thread_name(name: String) 🔗

Asigna el nombre dado al hilo actual. Devuelve @GlobalScope.ERR_UNAVAILABLE si no está disponible en la plataforma actual.


void set_use_file_access_save_and_swap(enabled: bool) 🔗

Si enabled es true, al abrir un archivo para escritura, se utiliza un archivo temporal en su lugar. Cuando se cierra, se aplica automáticamente al archivo de destino.

Esto puede ser útil cuando los archivos pueden ser abiertos por otras aplicaciones, como antivirus, editores de texto o incluso el propio editor de Godot.


Error shell_open(uri: String) 🔗

Solicita al sistema operativo abrir un recurso identificado por uri con el programa más apropiado. Por ejemplo:

  • OS.shell_open("C:\\Users\\name\\Downloads") en Windows abre el explorador de archivos en la carpeta Descargas del usuario.

  • OS.shell_open("C:/Users/name/Downloads") también funciona en Windows y abre el explorador de archivos en la carpeta Descargas del usuario.

  • OS.shell_open("https://godotengine.org") abre el navegador web predeterminado en el sitio oficial de Godot.

  • OS.shell_open("mailto:example@example.com") abre el cliente de correo electrónico predeterminado con el campo "Para" configurado en example@example.com. Véase RFC 2368 - El esquema de URL [code]mailto[/code] para obtener una lista de campos que se pueden agregar.

Utiliza ProjectSettings.globalize_path() para convertir una ruta de proyecto res:// o user:// en una ruta del sistema para usar con este método.

Nota: Usa String.uri_encode() para codificar caracteres dentro de URLs de forma segura y portable. Esto es especialmente necesario para los saltos de línea. De lo contrario, shell_open() puede no funcionar correctamente en un proyecto exportado a la plataforma Web.

Nota: Este método está implementado en Android, iOS, Web, Linux, macOS y Windows.


Error shell_show_in_file_manager(file_or_dir_path: String, open_folder: bool = true) 🔗

Solicita al sistema operativo que abra el administrador de archivos, navegue hasta la file_or_dir_path dada y seleccione el archivo o carpeta de destino.

Si open_folder es true y file_or_dir_path es una ruta de directorio válida, el sistema operativo abrirá el administrador de archivos y navegará hasta la carpeta de destino sin seleccionar nada.

Utiliza ProjectSettings.globalize_path() para convertir una ruta de proyecto res:// o user:// en una ruta del sistema para usar con este método.

Nota: Este método solo está implementado actualmente en Windows y macOS. En otras plataformas, recurrirá a shell_open() con una ruta de directorio de file_or_dir_path prefijada con file://.


void unset_environment(variable: String) const 🔗

Elimina la variable de entorno dada del entorno actual, si existe. El nombre de variable no puede estar vacío ni incluir el carácter =. La variable de entorno se eliminará para el proceso de Godot y cualquier proceso ejecutado con execute() después de ejecutar unset_environment(). La eliminación de la variable de entorno no persistirá en los procesos que se ejecuten después de que finalice el proceso de Godot.

Nota: Los nombres de las variables de entorno distinguen entre mayúsculas y minúsculas en todas las plataformas, excepto en Windows.