将多个 shell 脚本、sed 和用户输入组合到一个脚本中

Combining multiple shell script, sed and user input in a single script

目前我正在使用两个单独的 shell 脚本来完成工作。

1) 列出当前目录并将其保存为 .html 文件(首先仅列出根目录,然后列出完整目录)

tree -L 1 -dH ./ >> /Volumes/BD/BD-V1.html && tree -H ./ >> /Volumes/BD/BD-V1.html

2) 使用 sed 删除不需要的行(我在 mac)

sed -i '' '/by Francesc Rocher/d' /Volumes/BD/BD-V1.html && sed -i '' '/by Steve Baker/d' /Volumes/BD/BD-V1.html  && sed -i '' '/by Florian Sesser/d' /Volumes/BD/BD-V1.html

现在我想将它们合并为一个脚本,用户输入文件路径。我试图用 python 但没有成功

import subprocess
subprocess.call(["tree", "-d", "-L", "1"])

上面的可以列出目录但我无法保存输出(我必须在 python 中执行此操作),我尝试过类似的方法但没有成功。

 file = open('out.txt', 'w')
 import subprocess
 variation_string = subprocess.call(["tree", "-d", "-L", "1"])  
 file.write(variation_string)
 file.close()

我也不确定如何实现 sed :(

编辑:我是初学者

您可以使用 subprocess 模块执行此操作。您可以创建另一个进程来运行您的命令,然后与之通信。这将为您提供输出。

import subprocess
file = open('out.txt', 'w')
...
command = "tree -d -L 1"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
...
file.write(output)
file.close()

您可以简单地将标准输出重定向到一个文件对象:

from subprocess import check_call

with open("out.txt","w") as f:
    check_call(["tree", "-d", "-L", "1"],stdout=f)

在您的代码中,您基本上是在尝试编写 return code,因为这是对文件的调用 returns,这会引发错误,因为 write 需要一个字符串。如果你想存储 运行 命令的输出,你可以使用 check_output.