我想自动化一个必须使用python运行truncate命令的过程

时间:2019-03-05 09:10:08

标签: python python-2.7

我正在自动化一个进程,在该进程中我应该运行category product_id discount C-10 64 10 C-11 294 17 ls等Linux命令。

好吧,我受truncate命令的困扰,我从用户那里获取输入并想截断图像。

truncate命令将是

truncate

我的代码运行正常:

$ truncate -s <size> <image> in general. eg: #truncate -s 123456790 img_original.img.

但是,对于专家来说,这似乎很愚蠢,但是对我来说,作为Python的初学者和新手,我不知道为什么会出错:

import os
import subprocess
size= input('Please enter the size of the new image, in terms of Total Bytes =')
image= input("Enter the image file name =")
print(size)
print(image)
# expand the image to $size - truncate -s $size $image which will be new_image.
subprocess.call(["truncate", "--size",size,image] ,shell=True)

好吧,现在可以用python的其他实现来执行上述操作,或者建议我将两个变量转换为相同类型的方法。 (如果有类型转换的话)。

3 个答案:

答案 0 :(得分:0)

使用

subprocess.call(["truncate", "--size",str(size),str(image)] ,shell=True)

OR

size= str(input('Please enter the size of the new image, in terms of Total Bytes =')).strip() image= str(input("Enter the image file name =").strip()

答案 1 :(得分:0)

而不是像这样编写命令

["truncate", "--size",size,image]

您可以先创建命令,然后将其存储在变量中,例如

command = 'truncate -s {} {}'.format(size, image)

然后在subprocess.call方法中使用此命令变量。

而且给出图像的绝对路径

答案 2 :(得分:0)

您需要使用shell=True 将第一个参数连接到字符串

subprocess.call(" ".join(["truncate", "--size",str(size),image]) ,shell=True)

注意:

  1. str(size)-转换为字符串
  2. " ".join-串联成shell-命令

但是您可以:

subprocess.call(["truncate", "--size",str(size),image] ,shell=False)

选择适合自己需求的东西。

在使用shell=True之前先阅读Security Consideration