you can also directly run expressions without having to create a new .py file
like this:
blender "/path/to/file.blend" -b --python-expr "import bpy;print(bpy.data.filepath)"
In case anyone wants to run a script which involves indentations, for e.g. a loop:
blender "/path/to/file.blend" -b --python-expr $'import bpy\nfor obj in bpy.data.objects:\n print(obj.name)'
You can also run one script from a blender file to change another blend file!
import bpy,subprocess
file_path="/path/to/another/file.blend"
code='''
import bpy
for obj in bpy.data.objects:
print(obj.name)
'''
output = subprocess.check_output(f"blender '{file_path}' -b --python-expr '{code}'", shell=True)
print(output.decode('UTF-8'))
Heck, if you're crazy enough you can run a script from one blend file to run a script in another blend file all in a one liner from the command line
blender "/path/to/file.blend" -b --python-expr $'import bpy,subprocess\nprint("Objects in file ",bpy.data.filepath)\nfor obj in bpy.data.objects:\n print(obj.name)\nfile_path="/path/to/another/file.blend"\ncode="""\nimport bpy\nprint("Objects in file ",bpy.data.filepath)\nfor obj in bpy.data.objects:\n print(obj.name)\n"""\noutput = subprocess.check_output(f"blender \'{file_path}\' -b --python-expr \'{code}\'", shell=True)\nprint(output.decode(\'UTF-8\'))\n'
The possibilities are endless