【问题标题】:subprocess.call() for shell program which write a filesubprocess.call() 用于编写文件的 shell 程序
【发布时间】:2014-01-06 10:11:48
【问题描述】:

我需要使用 python 执行一个 shell 脚本。 shell 程序的输出是一个文本文件。脚本没有输入。帮我解决这个问题。

def invokescript( shfile ):
  s=subprocess.Popen(["./Script1.sh"],stderr=subprocess.PIPE,stdin=subprocess.PIPE);
  return;

invokescript("Script1.sh");

在使用上述代码时,我收到以下错误。

Traceback (most recent call last):
  File "./test4.py", line 12, in <module>
    invokescript("Script1.sh");
  File "./test4.py", line 8, in invokescript
    s=subprocess.Popen(["./Script1.sh"],stderr=subprocess.PIPE,stdin=subprocess.PIPE);
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error

提前谢谢...

【问题讨论】:

  • python中不需要分号
  • ITYM s = subprocess.Popen([shfile], ...)。否则你就不需要那个参数了。
  • 顺便说一句,如果调用者需要它,你应该返回这个s

标签: python shell popen


【解决方案1】:

试试这个:

import shlex

def invokescript(shfile):
    return subprocess.Popen(
        shlex.split(shfile),
        stderr=subprocess.PIPE,
        stdin=subprocess.PIPE
    )

invokescript("Script1.sh");

当然还要将#!/usr/bin/env bash 添加到您的 bash 文件中。

【讨论】:

  • 我认为 shebang 是这里的解决方案。 shlex.split() 电话的意义何在?这里没有什么可拆分的......
  • 好的,我编辑了代码。我添加了“shlex.split”,因为现在功能更通用了。
  • 我仍然面临同样的错误。感谢您的回复
【解决方案2】:

我使用 os.system() 来调用 shell 脚本。这符合我的预期。确保您在 python 代码中导入了 os 模块。

invokescript( "Script1.sh" ) // Calling Function

function invokescript( shfile ):  // Function Defenition
     os.system("/root/Saranya/Script1.sh")
     return;

以下也是可执行的:

invokescript( "Script1.sh" ) // Calling Function

function invokescript( shfile ):  // Function Defenition
     os.system(shfile)
     return;

感谢您的即时回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    相关资源
    最近更新 更多