Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

f string formatting not working as intended

I’m fairly new to Python and need some advise,

os.system(f"find {files_local} -type f -exec chmod 0644 {} \;")

this line doesn’t work because of the empty {}

os.system(f"find {files_local} -type f -exec chmod 0644 {} \;")
SyntaxError: f-string: valid expression required before '}'

What work around I could use?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue you’re facing is that Python’s f-strings expect valid expressions inside {}. In your os.system command, the {} inside the shell command is mistakenly interpreted as part of the Python f-string syntax, causing the syntax error.

To fix this, you can escape the {} by doubling them ({{}}), so Python doesn’t treat them as placeholders for f-strings. Here’s the corrected version:

import os

os.system(f"find {files_local} -type f -exec chmod 0644 {{}} \\;")

That being said using os.system for tasks like this can be risky (e.g., injection vulnerabilities). Instead consider using Python’s subprocess module, which is safer and provides more control:

import subprocess

subprocess.run(["find", files_local, "-type", "f", "-exec", "chmod", "0644", "{}", ";"], check=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading