【问题标题】:Running bash script from python从 python 运行 bash 脚本
【发布时间】:2013-03-14 16:31:32
【问题描述】:

我遇到了以下问题:

我有这个简单的脚本,叫做 test.sh:

#!/bin/bash

function hello() {
    echo "hello world"
}
hello

当我从 shell 运行它时,我得到了预期的结果:

$ ./test2.sh
hello world

但是,当我尝试从 Python (2.7.?) 运行它时,我得到以下信息:

>>> import commands
>>> cmd="./test2.sh"
>>> commands.getoutput(cmd)
'./test2.sh: 3: ./test2.sh: Syntax error: "(" unexpected'

我相信它以某种方式从“sh”而不是 bash 运行脚本。我是这么认为的,因为当我使用 sh 运行它时,我会收到相同的错误消息:

$ sh ./test2.sh
./test2.sh: 3: ./test2.sh: Syntax error: "(" unexpected

此外,当我从 python 运行带有前面“bash”的命令时,它可以工作:

>>> cmd="bash ./test2.sh"
>>> commands.getoutput(cmd)
'hello world'

我的问题是:尽管我在脚本的开头添加了#!/bin/bash 行,但为什么 python 选择使用 sh 而不是 bash 来运行脚本?我怎样才能使它正确(我不想在 python 中使用前面的 'bash',因为我的脚本是由我无法控制的远程机器从 python 运行的)。

谢谢!

【问题讨论】:

  • 呃,你的 shebang 看起来全错了。 #~/bin/bash,这甚至不是一个shebang,而是一个简单的评论。应该是#!/bin/bash
  • 对不起。只是一个错字
  • 它可以在我的 Ubuntu 12.10 32 位上正常运行。可能是您的默认环境导致使用 sh 而不是 bash。
  • 试试 os.system() 它的工作原理
  • 哦,我明白了,那很奇怪。你在那里使用什么发行版?

标签: python bash sh


【解决方案1】:

似乎还有一些其他问题 - shbang 和 commands.getoutput 应该可以正常工作,如您在此处显示的那样。将 shell 脚本更改为:

#!/bin/bash
sleep 100

然后再次运行该应用程序。检查ps f 实际的进程树是什么。 getoutput 确实调用了sh -c ...,但这不应该改变哪个shell 本身执行脚本。

从问题中描述的最小测试中,我看到以下流程树:

11500 pts/5    Ss     0:00 zsh
15983 pts/5    S+     0:00  \_ python2 ./c.py
15984 pts/5    S+     0:00      \_ sh -c { ./c.sh; } 2>&1
15985 pts/5    S+     0:00          \_ /bin/bash ./c.sh
15986 pts/5    S+     0:00              \_ sleep 100

因此,单独来看,这可以按预期工作 - python 调用 sh -c { ./c.sh; },由第一行 (bash) 中指定的 shell 执行。

确保您正在执行正确的脚本 - 由于您使用的是 ./test2.sh,请仔细检查您是否在正确的目录中并执行正确的文件。 (print open('./test2.sh').read() 会返回您所期望的吗?)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2012-11-24
    • 2011-09-16
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多