Windows 上的 Python 子进程问题

问题描述 投票:0回答:4

我正在尝试编写一个 Python 脚本来转换一堆图像。

类似于下面的代码(经过巨大的最小化之后):

#!/usr/bin/python
# -*- coding: utf-8 -*-
from subprocess import call

cmd = ' '.join(['convert.exe', '-resize', '110', 'foo\\a.jpg', 'bar\\a.jpg'])
print cmd
call(cmd)

执行后出现以下错误:

Parameter not valid - 110

当我在命令行上复制/粘贴从脚本发出的字符串时,图像转换工作完美。 我错过了什么?

python subprocess
4个回答
1
投票

我想说这个错误很可能是两件事造成的结果

  1. 在 call 命令中,尝试使用
    shell=True
    作为第二个参数。
  2. 您使用的是相对路径,并且 python 的工作目录可能与 cmd shell 中的工作目录不同。

0
投票

您确定脚本调用的convert.exe 与您从命令行调用的convert.exe 相同吗?出于痛苦的经验,我总是使用我想从脚本、Python 或其他方式调用的可执行文件的完整路径。


0
投票

Windows XP 有一个名为convert 的命令shell 命令。当我向它提供命令时,我收到与您看到的相同的错误消息。我怀疑它被调用而不是你的convert.exe。


0
投票

导入子流程 导入日志记录 从日期时间导入日期时间,时间增量

配置日志记录

logging.basicConfig(filename='/var/log/cleanup.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def run_command(命令): """运行 shell 命令并返回输出或日志错误。""" 尝试: 结果= subprocess.run(命令,shell = True,检查= True,capture_output = True,text = True) 如果结果.stdout: 返回结果.stdout.strip() 别的: logging.warning(f"命令已执行但没有输出:{command}") 返回无 除了 subprocess.CalledProcessError 为 e: # 如果错误是由于目录不存在造成的(test -d 返回 1) 如果命令中有“test -d”且 e.returncode == 1: logging.info(f"目录 {command.split()[-1]} 不存在。跳过删除。") 别的: logging.error(f"执行命令时出错:{command}。错误:{e.stderr.strip()}") 无返回

def确定要删除的目录(): """根据current_month - 5计算要删除的目录。""" target_date = (datetime.now() - timedelta(days=5*30)).strftime('%Y/%m') logging.info(f"确定要删除的目录:{target_date}") 返回目标日期

def cleanup_directory(目录名): """删除存档目录中指定的目录(如果存在)。""" 档案目录=“/路径/到/档案目录” full_path = f"{archive_directory}/{directory_name}"

# Check if the directory exists
if run_command(f"test -d {full_path}") is None:
    return

# Log the size before deletion
size_before = run_command(f"du -sh {full_path} | cut -f1")
if size_before:
    logging.info(f"Size of {directory_name} before deletion: {size_before}")

# Attempt to delete the directory
if run_command(f"rm -rf {full_path}") is not None:
    logging.error(f"Failed to delete: {full_path}")
else:
    logging.info(f"Successfully deleted: {full_path}")

if name == "main": 尝试: 要删除的目录=确定要删除的目录() cleanup_directory(要删除的目录) 除了异常 e: logging.error(f"发生意外错误:{e}")

© www.soinside.com 2019 - 2024. All rights reserved.