pythonsips

Sips command in a Python script is not working - “Error 4: no file was specified” and "not a valid file - skipping"


Trying to resize (only Width) some images by a Python script. This is a Python script:

# -*- coding: utf-8 -*-

import subprocess
import os


# New width
new_width = '200'

# Create for converted images
create_directory_out = subprocess.run(['mkdir', '-p', './Result'])

# Directory with started images
directory_source = 'Source'

#  Directory with converted images
directory_out = 'Result'

# get list of started images to variable files
files = os.listdir(directory_source)

# Filtre by mask .jpg to variable images
images = filter(lambda x: x.endswith('.jpg'), files)

img_list = list(images)

# Loop of convert images by sips
for file_name in img_list:
    print(file_name)
    subprocess.run(['sips', '--resampleWidth', 'new_width', '--out', './directory_out/file_name', './directory_source/file_name', ])

I get an error:

face-04.jpg
Warning: ./directory_source/file_name not a valid file - skipping
Error 4: no file was specified
Try 'sips --help' for help using this tool
face-04.jpg

But sips command in Terminal is working:

sips --resampleWidth 200 --out ./Result/face-04.jpg ./Source/face-04.jpg 

What else could be going wrong?

Thanks in advance for the help.


Solution

  • you're mixing up literals with variables:

    subprocess.run(['sips', '--resampleWidth', 'new_width', '--out', './directory_out/file_name', './directory_source/file_name', ])
    

    tries to access './directory_out/file_name' literally!

    you need to actually use your variables and join directory & file names:

    subprocess.run(['sips', '--resampleWidth', 'new_width', '--out', os.path.join(directory_out,file_name), os.path.join(directory_source,file_name)])
    

    Aside:

    create_directory_out = subprocess.run(['mkdir', '-p', './Result'])
    

    could be replaced by a native python call:

    os.makedirs(directory_out)