从作为参数传递给函数的列表中填充bash命令

我有一个列表,该列表作为参数传递给函数。从这个列表中,我需要填充一个bash命令并执行

lst = ['test01.gz','test02.gz','test03.gz','newtest01.gz','newtest02.gz','random.gz']

def populate_command(lst):
    cmd = 'cat {} {} > filename.gz'
    subprocess.run(cmd,shell=True,check=True)

cat命令中应填充cat test01.gz test02.gz test03.gz > test.gz。对于newtest01.gzcat newtest01.gz newtest02.gz > newtest.gz)同样,如果只有一个.gz文件(random.gz),则不执行任何操作

我无法使用列表中的参数填充cat命令。 任何帮助将不胜感激

=================================

修改后的代码

想出了以下解决方案,但我想for循环太多了。任何其他有效的方法

我有一个文件列表 s3_files_list=[''test01.gz','random.gz'']

由此我得到文件的名称,这些文件被分成多个文件,例如test01,test02等

from typing import List

def find_split_files(temp_list) -> List[str]: main_lst=set()
for x in temp_list: if x[:-3][-3:]!='000': main_lst.add(x[:-6]) return main_lst

split_files=find_split_files(s3_files_list)

split_files给了我['test','newtest']

def files_to_zip(split_files,s3_files_list): main_lst=[] for y in split_files: temp_lst=[] for x in s3_files_list: if x.startswith(y): temp_lst.append(x) main_lst.append(temp_lst)

Main_lst返回[['test01.gz','test02.gz','test03.gz'],['newtest01.gz','newtest02.gz']]

def populate_command(main_lst): for p in main_lst: cmd = 'cat ' for f in p: cmd = cmd + f + ' ' cmd = cmd + ' > ' + f[:-6]+'.gz' print(f'command is {cmd}') subprocess.run(cmd,check=True)

ycwb123 回答:从作为参数传递给函数的列表中填充bash命令

您可以使用for语句遍历lst并构建cmd字符串,如下所示:

> def populate_command(lst):
>     cmd = 'cat '
>     for f in lst:
>         cmd = cmd + f + ' '
>     cmd = cmd + ' > filename.gz'
>     subprocess.run(cmd,shell=True,check=True)
本文链接:https://www.f2er.com/3128137.html

大家都在问