[英]how to execute linux command via python loop
I have a list of files which will be used to extract by another linux script like this:我有一个文件列表,这些文件将被另一个 linux 脚本用来提取,如下所示:
gzip -dc input/test_log.gz | bin/recreate state/object_mappings.sort > output/recreate.out
I need to change the name test_log.gz
with my list of files with python loop, how can I execute this script dynamically.我需要使用 python 循环的文件列表更改名称
test_log.gz
,如何动态执行此脚本。 here is my code:这是我的代码:
import os
from subprocess import call
files = os.listdir("/my directory/")
files.sort()
for i in files:
call('gzip -dc input/test_log.gz | bin/recreate state/object_mappings.sort > output/recreate.out')
I dont know how to change this script with dynamic variable i??我不知道如何使用动态变量 i 更改此脚本?
You can use an f-string
literal:您可以使用
f-string
文字:
import os
from subprocess import call
files = os.listdir("/my directory/")
files.sort()
for file in files:
call(f'gzip -dc {os.path.abspath(file)} | bin/recreate state/object_mappings.sort > output/recreate.out')
In my case the below method works.在我的情况下,以下方法有效。
from subprocess import call
files = ['input.txt', 'input1.txt', 'input2.txt', 'input3.txt']
for file in files:
call(['sed', '-i', 's+NameToBeReplaced+NewName+', file])
sed : is stream editor sed : 是流编辑器
-i : Allows to edit the source file -i : 允许编辑源文件
+ : Is delimiter. + : 是分隔符。
call : Takes command in array format. call :采用数组格式的命令。
For example: if you want to run ls -l input.txt
例如:如果你想运行
ls -l input.txt
call(['ls', '-l', file])
I hope the above information works for you 😃.希望以上信息对你有用😃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.