How to Run a Binary from an Exported Project

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By velleitious

When I call an external binary via OS.execute(res://path/to/bin) in the editor it executes correctly. However, after executing the project, it fails to run the binary, returning exit code -1. This is despite that the binary is listed as a non-resource file to be exported. How do I run the binary from the exported project?

:bust_in_silhouette: Reply From: a_world_of_madness

OS.execute expects a path to an executable on the filesystem, it’s not designed to run an executable embedded in the exported PCK file. Instead, you’ll need to include the executable with the exported project. If you manually place the executable in the export root directory beside the game’s executable, this should find the correct path depending on if you are running in editor or exported:

var path = ""
if OS.has_feature("editor"):
	path = ProjectSettings.globalize_path("res://program.exe")
else:
	path = OS.get_executable_path().get_base_dir().path_join("program.exe") 

It is possible to extract the packaged exe from the PCK before executing like this:

var path = ""
if OS.has_feature("editor"):
	# In editor, use the unpackaged program path
	path = ProjectSettings.globalize_path("res://program.exe")
else:
	path = OS.get_executable_path().get_base_dir().path_join("program.exe")
	if not FileAccess.file_exists(path):
		# Extract the exe to the program directory
		var bytes = FileAccess.get_file_as_bytes("res://program.exe")
		var out_file := FileAccess.open(path, FileAccess.WRITE)
		out_file.store_buffer(bytes)
		out_file.close()
	
var output = []
var args = []
OS.execute(path, args, output, false, true)

But I wouldn’t recommend it, since you will now be storing 2 copies of the executable, one in the filesystem and one in the PCK. Also, this can cause permission issues if the exported game doesn’t have write access to it’s own folder. I’d recommend simply storing the executable alongside the exported game in a zip archive if you need to distribute it.