【问题标题】:Combining multiple shell script, sed and user input in a single script在单个脚本中组合多个 shell 脚本、sed 和用户输入
【发布时间】:2015-03-01 00:25:04
【问题描述】:

目前我正在使用两个单独的 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 :(

编辑:我是初学者

【问题讨论】:

  • 由于您显然是 shell 命令和 Python 的初学者,我建议您现在不要同时使用这两种命令。继续使用 shell,花点时间编写一个 shell 脚本来做你想做的事。 Shell 脚本可以很好地接受用户输入,例如通过参数之类的命令。
  • @Jan-PhilipGehrcke 谢谢,现在我都在 shell 脚本中完成了。

标签: python bash shell sed


【解决方案1】:

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

from subprocess import check_call

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

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

【讨论】:

    【解决方案2】:

    您可以使用 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2017-12-07
      • 2023-03-16
      • 2023-03-18
      • 2021-06-03
      相关资源
      最近更新 更多