Search code examples
pythonvariablesstat

Using a stat with a variable


I am writing a script that checks the octal permissions of files and folders in Linux. I am struggling with this line of code:

stat -c %a check

Check is raw input from the user, for example /home. When I run the script in terminal I get the following error message when the line above is executed:

file "check.py", line 17
stat -c %a check
               ^
SyntaxError: invalid syntax

I also tried putting check in brackets and I then got:

Traceback (most recent call last):
  File "check.py", line 34, in <module>
main()
  File "check.py", line 31, in main
    folderexists(check)
  File "check.py", line 17, in folderexists
    stat -c %a (check)
NameError: global name 'c' is not defined

Solution

  • That line should be executed in the terminal, not in a Python script. It contains invalid Python syntax.

    If you want to issue a system command from Python, you can use os.system:

    import os
    os.system('stat -c %a check')
    

    If you need to add values into the command string, use str.format:

    import os
    os.system('stat -c {} check'.format(value))