【问题标题】:Running a bash file with Python使用 Python 运行 bash 文件
【发布时间】:2014-02-25 16:47:52
【问题描述】:

我有一个通常使用 Cygwin 执行的 bash 文件。 我需要从我的 Python 代码中运行这个文件。

我试过了:

for bashfile in files:
    p = Popen(bashfile, cwd=dname) #dname is the current directory of the script
    stdout, stderr = p.communicate()

我也看到了类似的问题here,但是当尝试以这种方式运行它时,它说它找不到我的 bash 文件的目录...

有什么想法吗?谢谢! :-)

编辑:bashfile 有完整路径。

【问题讨论】:

  • 你的脚本在哪里,你的 bash 文件在哪里?
  • bash 文件位于脚本目录的子目录之一中。关键是他们在不同的地方。有关系吗?
  • 如果bashfile 只是脚本的名称(例如foo.sh),请尝试指定脚本的路径..../subdir/foo.sh
  • 能否提供完整的错误信息?

标签: python bash cygwin popen


【解决方案1】:

您是否需要它的输出才能将其直接传递给 Python?如果不是,这可能是非常快速和简单的解决方案:

os.system("""here some code you use to execute in Terminal""")

【讨论】:

  • 您可以随时查看os.getcwd(),甚至可以通过os.chdir("/foo")将其更改为其他内容
  • 如果你决定使用 os.system,这个例子可能有用:superuser.com/questions/513315/…
  • 非常感谢@andi!我给出的链接中的那个奇怪的解决方案让我完全困惑......非常感谢,现在可以使用了! :-)
  • @Cheshie 很高兴为您提供帮助 :-)
  • @Cheshie:我不明白。如果Popen(bashfile, cwd=dname) 找不到bashfileos.system(bashfile) 怎么可能工作?
【解决方案2】:

你也可以试试这个,虽然它(并且无论你尝试什么)对目录的位置很重要。就输出而言,这可能比os 方法更简洁。

import commands
cmd="bash ./script.sh"
commands.getoutput(cmd)

如果是需要换目录的话:

cmd = "/path/to/your/script/script.sh"

os 相比,使用此方法的额外好处是您可以将输出分配给变量...

fun_times = commands.getoutput("bash ./script.sh")

而……

not_fun_times = os.system("./script.sh")

会抛出错误。

等等等等

【讨论】:

  • 谢谢,但是:"'{' is not recognized as an internal or external command,\noperable program or batch file." ?您的解决方案看起来我可以将输出转换为 Python,但我不明白错误...
  • 哪里有{
  • 不知道...我在一个脚本上测试了它,其内容是:echo "hello" 或类似的东西...
  • 你能给出完整的错误吗?因为它对我来说效果很好。
  • 我给了你完整的错误。我写的代码如你所说:import commands // cmd="bash C:/Documents and Settings/Administrator/Desktop/hi.sh" // commands.getoutput(cmd)(我在这里添加了“//”来分隔行间)。
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 2018-03-14
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
相关资源
最近更新 更多