【问题标题】:Can run multiple OS command using variable in Python?可以在 Python 中使用变量运行多个操作系统命令吗?
【发布时间】:2020-07-21 09:43:22
【问题描述】:

您好,我正在尝试在 Mac OS 中使用 Python 运行多个操作系统命令

我想在终端中使用转换命令将图像转换为 tif 文件。不过我有 100 张图片要转换,我编写了 Python 程序以使其更容易。

import os
import subprocess

files = os.listdir("/Users/woonie/Downloads/test")

i=1
for file in files:
    args=['convert',file,'-resize','100%','-type',"Grayscale","/Users/woonie/Downloads/test/kor.",i,"test.exp0.tif"]
    subprocess.Popen(args)
    i = i+1

convert filename -...- output_filename.exp0.tif 是转换命令的形式,所以我每次都需要更改文件名和 output_filename。我在文件中有文件名列表。我想在“测试”之后放置图像数量,使其变为 kor.test1.exp0.tif、kor.test2.exp0.tif 等。

Traceback (most recent call last):
  File "/Users/woonie/PycharmProjects/image_chage/change.py", line 9, in <module>
    subprocess.Popen(args)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1637, in _execute_child
    self.pid = _posixsubprocess.fork_exec(
TypeError: expected str, bytes or os.PathLike object, not int

但是出现了这个错误。

所以我把代码改成了

args=['convert'+str(file)+'-resize','100%','-type',"Grayscale","/Users/woonie/Downloads/test/kor."+str(i)+"test.exp0.tif"]

但同样的错误出现了...... 当我将该命令直接放入终端时,它就起作用了。

我是不是用错了子进程?或者我无法制作我想要的程序

【问题讨论】:

  • 你确定这是你的真实代码吗? args=['convert'+str(file)+'-resize' 将产生 convertFILENAME-resize 作为第一个参数,这是行不通的。
  • 是的,这是我的代码。那我应该把它写下来喊','吗?

标签: python command-line subprocess imagemagick imagemagick-convert


【解决方案1】:

使用

subprocess.run(args)

而不是

subprocess.Popen(args)

话虽如此,您的args 数组应该看起来像

args=['convert', str(file), '-resize','100%','-type',"Grayscale","/Users/woonie/Downloads/test/kor."+str(i)+"test.exp0.tif"]

因为文件名和调整大小选项可能是单独的参数。

【讨论】:

  • 谢谢,我认为您的回答很有帮助。但遗憾的是我有新的错误
  • convert:此图像格式没有解码委托' @ error/constitute.c/ReadImage/562. convert: no images defined /Users/woonie/Downloads/test/kor.test1.exp0.tif'@error/convert.c/ConvertImageCommand/3282。 ...等
  • @Meteor정 那是一个 ImageMagick 错误,问另一个关于 IM 的问题。注意ImageMagick has a Python API...
【解决方案2】:

您的代码存在很多问题。


与其在输入和输出文件的深处携带多层次的长路径名,不如将目录更改为文件所在的位置并处理简单的文件名——这样更不容易出错,也更少维护噩梦。

因此,请考虑使用类似以下内容的代码开始:

import os

# Go to where the images are
os.chdir('/Users/woonie/Downloads/test')

与使用os.listdir() 相比,如果您使用与在shell 中完全相同的通配符,您将获得更大的灵活性。因此,如果您只想处理 JPEG 而不是您在上一次运行中生成的 TIFF,请使用:

import glob

# Get list of JPEGs to process
JPEGs = glob.glob('*jpg')

我不确定你为什么使用subprocess.Popen() - 当你想要捕获输出时通常会这样做,你不妨使用subprocess.run()


我不知道你为什么使用-resize 100%。那个是从哪里来的?无论如何,图像应该是 100%。


当你想制定你的输出文件名时,你可以更简单地使用f-strings。因此,摆脱所有长路径后,您的最后一个参数变为:

f'kor.{i}test.exp0.tif'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2014-01-23
    • 2011-08-31
    • 1970-01-01
    • 2013-02-01
    相关资源
    最近更新 更多