Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking g++ via `subprocess.run` in Python causes "exec format error" in executable

Using Python 3.7, I am trying to invoke g++ to compile and build a C++ file via

#!/usr/bin/env python3

import subprocess

if __name__ == '__main__':
    subprocess.run(
        executable="/usr/bin/g++",
        args=["/some/path/source.cpp", "-std=c++17"],
        shell=True
    )

When I run the script, the executable builds. I then chmod u+x it. However, when I try to execute the executable, it fails and says:

-bash: ./a.out: cannot execute binary file: Exec format error

I've read some other posts regarding this error however none are applicable. For some reason, this method fails, however when I run g++ natively in my terminal, it works as expected.

Edit: When I invoke file a.out, the output is

a.out: ELF 32-bit LSB relocatable, ARM, EABI5 version 1 (SYSV), not stripped

Appreciate any help, thanks!

like image 368
Richard Robinson Avatar asked Jan 29 '26 20:01

Richard Robinson


1 Answers

The executable parameter to subprocess is only rarely needed. With shell=False, it overrides args[0] as the program to run (allowing argv[0] to be customized, as for a login shel). With shell=True (which should be avoided when possible, partly because it doesn’t do what you think with your carefully separated args list), it replaces the implicit /bin/sh invoked to run the command. The standard option to run one command is -c, so you ran

/usr/bin/g++ -c /some/path/source.cpp -std=c++17

which indeed produces a relocatable (i.e., a .o file). a.out is not the normal name for such, but perhaps it’s a fallback when the directory containing the source is not writable.

like image 178
Davis Herring Avatar answered Jan 31 '26 09:01

Davis Herring