Skip to content

Inaccurate process.command when using python -m <module> #4518

Description

@AvihuHenya

Describe your environment

OS: Linux
Python version: 3.13.2
SDK version: 1.28.2
API version: 1.28.2

What happened?

I've encountered an issue with the process.command and related attributes when running Python applications as modules using the -m flag. For example, in a Docker context with:
ENTRYPOINT ["python", "-m", "myapp"]

The collected value for process.command ends up being -m, rather than the actual module name or full command line. This affects observability, as the telemetry data doesn't reflect the real process invocation.

Image

Steps to Reproduce

Create a minimal Python module:

mkdir myapp
echo 'print("Hello")' > myapp/__main__.py

Run it using the -m flag:
python -m myapp

Observe that sys.argv[0] is -m, which causes OpenTelemetry to set:
process.command = "-m"
instead of the expected executable path

Expected Result

If you run:
python -m myapp

Then:

Expected process.command:
/usr/bin/python3 (or similar full path to the Python executable)

Expected process.command_line:
python -m myapp (the full command line as invoked)

Expected process.command_args:
['-m', 'myapp'] (everything after the command)

Actual Result

-m for all three attributes

Additional context

From what I can tell, this happens because the resource detector relies on sys.argv, and when Python is invoked with -m, sys.argv[0] is set to -m (or sometimes the path to main.py), which doesn't give the full picture.

Possible Workaround
I've been experimenting with the idea of directly reading from /proc/self/cmdline on Linux to extract the true command line. Here’s a snippet that demonstrates this approach:

if sys.argv and sys.argv[0] == "-m":
            try:
                with open("/proc/self/cmdline", "rb") as command_file:
                    raw_cmdline = command_file.read()

                if raw_cmdline:
                    command_line = raw_cmdline.decode(errors="ignore").split('\0')
                    if command_line and command_line[0]:
                        attributes[ResourceAttributes.PROCESS_COMMAND] = command_line[0]
                        attributes[ResourceAttributes.PROCESS_COMMAND_LINE] = " ".join(command_line)
           

Suggestions
Would it make sense to incorporate logic like this into the default resource detector?

Alternatively, is there a better approach to improve detection for -m module usage?

Happy to contribute a PR if this seems like a reasonable enhancement.

Would you like to implement a fix?

Yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions