python,从目录中读取文件名,在bash脚本中使用字符串 [英] python, read the filename from directory , use the string in bash script
问题描述
我正在编写一个bash脚本(例如 program.sh
),在这里我要调用一个python代码,从该目录中读取文件列表.
I am writing a bash script (e.g. program.sh
) where I am calling a python code in which a list of files are read from a directory.
python脚本( read_files.py
)如下:
the python script (read_files.py
) is as following:
import os
def files(path):
for filename in os.listdir('/home/testfiles'):
if os.path.isfile(os.path.join('/home/testfiles', filename)):
yield filename
for filename in files("."):
print (filename)
现在,我想保留字符串文件名,并在bash脚本中使用它.
Now I want to keep the string filename and use it in the bash script.
例如 program.sh
:
#!/bin/bash
python read_files.py
$Database_maindir/filename
.
.
.
我如何保留字符串文件名(目录中文件的名称)并编写循环以在bash脚本中为每个文件名执行命令?
How could I keep the string filename (the names of files in the directory) and write a loop in order to execute commands in bash script for each filename?
推荐答案
问题中的Python脚本无法完成Bash本身无法完成的所有工作,并且变得越来越简单.改用简单的本机Bash:
The Python script in the question doesn't do anything that Bash cannot already do all by itself, and simpler and easier. Use simple native Bash instead:
shopt -s nullglob
for path in /home/testfiles/*; do
if [[ -f "$path" ]]; then
filename=$(basename "$path")
echo "do something with $filename"
fi
done
如果Python脚本的功能超出了您在问题中所写的内容,例如,它执行一些复杂的计算并吐出文件名,在Bash中做起来会很复杂,那么您确实有一个合法的用例来保留它.在这种情况下,您可以像这样遍历输出中的行:
If the Python script does something more than what you wrote in the question, for example it does some complex computation and spits out filenames, which would be complicated to do in Bash, then you do have a legitimate use case to keep it. In that case, you can iterate over the lines in the output like this:
python read_files.py | while read -r filename; do
echo "do something with $filename"
done
这篇关于python,从目录中读取文件名,在bash脚本中使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!