0

I've suddenly started getting an error on all versions of Python on MacOS reporting the following when using subprocess:

FileNotFoundError: [Errno 2] No such file or directory: '/usr/sbin/sysctl -n machdep.cpu.brand_string'

However, /usr/sbin/sysctl does exist, I can run the command myself, under my normal user, without any issue - just not with a Python interpreter. When launching a Python interpreter owned by root I don't get this issue.

The permissions and ownership are reported as the following:

-rwxr-xr-x 1 root wheel 135296 Oct 28 09:43 /usr/sbin/sysctl*

Changing the permissions/ownership doesn't appear possible even undo sudo anyway; as Operation not permitted is reported.

luke
  • 1,005
  • 7
  • 19
  • Please post your python code. – Istvan Jan 09 '23 at 15:56
  • 2
    There indeed is no such file as `/usr/sbin/sysctl -n machdep.cpu.brand_string`. You're somehow passing the entire command line as the name of the executable. Show us the code where you try to run this command. – jasonharper Jan 09 '23 at 16:04
  • BTW, both your answers are kind of awful (in different ways / different levels; `shlex.split('...')` is better than `'...'.split()`, and both of those are better than `shell=True`, but better than all of those is to specify an argument vector explicitly, since it gets you into habits that work right even when passing weird data as arguments); I'd urge you to use answers on the linked duplicate, as it's been around longer with more time for voting/comments/edits/etc. – Charles Duffy Jan 09 '23 at 16:43

1 Answers1

0

There are extra limitations for applications which path those can read from. You must specifically allow certain paths to applications. I think this is why you can't open it from Python.

Another potential root cause might be that you do not use subprocess correctly.

Here is the correct way of using it:

import shlex
import subprocess
subprocess.run(shlex.split("/usr/sbin/sysctl -n machdep.cpu.brand_string"))
# Apple M1
# CompletedProcess(args=['/usr/sbin/sysctl', '-n', 'machdep.cpu.brand_string'], returncode=0)
Istvan
  • 7,500
  • 9
  • 59
  • 109
  • _grumble_ re the first paragraph, which is mostly wrong (I say "mostly" insofar as it's vague enough that various sandboxing approaches could _possibly_ fit the description, but even then they mostly wouldn't cause the specific error at hand). The code sample at the end is correct, even if manual splitting into an argument vector is the better practice. – Charles Duffy Jan 09 '23 at 16:36