【问题标题】:Can't launch a program from a different directory via Pexpect无法通过 Pexpect 从其他目录启动程序
【发布时间】:2015-06-02 13:28:55
【问题描述】:

我无法通过 Pexpect 模块启动一个简单的 HelloWorld 程序。 我有一个包含 HelloWorld 二进制文件的目录 - hw,期望脚本 - m.py,以及一个包含相同脚本的目录。

├── hw
├── m.py
├── main.cpp
└── dir
    └── m.py

这是我的期望脚本:

import pexpect
child = pexpect.spawn("./hw", cwd = /absolute/path/to/parent/directory")
child.expect("!")
print(child.before)

如果我从父目录运行脚本,一切正常。但是,如果我从任何其他目录(例如此处的 dir)运行它,则会收到以下错误:

pexpect.ExceptionPexpect: The command was not found or was not executable: ./hw.

我该如何应对?

我已经在 Mac OS 和 Ubuntu 上尝试过。 HelloWorld 二进制工作正常,它被设置为可执行文件。 Python 2.7.6,预计 3.3

【问题讨论】:

  • 我假设cwd 设置为衍生进程的工作目录,但实际上并未设置为调用进程的工作目录。这意味着您不能使用./hw,而需要在该参数中使用/absolute/path/to/parent/directory/hw
  • @EtanReisner 我不确定如果我理解正确,但在我的情况下,cwd 参数指向硬件所在的目录(树描述了这个目录),我称之为父目录,因为我尝试从其中的目录启动脚本,但它失败了。
  • @EtanReisner 的观点是,从包含hw 的目录以外的任何目录启动一个路径名为./hw 的程序肯定会失败。
  • 对。 cwd 不会更改当前目录,而是为运行进程设置目录。这无助于./hw 找到二进制文件,但如果您不在正确的目录中。在这种情况下,您需要先更改目录,或者使用从当前位置到二进制文件的正确绝对或相对路径。
  • @EtanReisner: the source 表示命令的完整路径是在 之前 分叉(在父级中)确定的,os.chdir(cwd) 被称为 after 叉子(在孩子中),即您的初始评论是正确的。

标签: python bash command-line-interface pexpect


【解决方案1】:

要运行可执行文件hw,其父目录应位于PATH envvar 中,或者您应提供完整路径。如果路径是相对路径(不推荐),那么它是相对于您当前工作目录的路径,无论 cwd 值如何。

如果你想从其目录运行hw

import os
import pexpect # $ pip install pexpect

hw = '/absolute/path/to/parent/directory/hw'
child = pexpect.spawn(hw, cwd=os.path.dirname(hw))
# ...

【讨论】:

    【解决方案2】:

    @jfs的回答很清楚,只是想补充一些,

    如果您在目录/path/to/parent/dir 中有一个可执行脚本(script.sh

    child = pexpect.spawn("./script.sh", cwd="/path/to/parent/dir")  # wont work
    

    ./ 一样,它试图从脚本当前工作目录执行,如果你需要它来工作,那么你可以添加os.chdir(),所以

    os.chdir("/path/to/parent/dir")
    child = pexpect.spawn("./script.sh")  # works
    

    如果您不需要更改脚本路径全部运行子进程,可以生成 pexpect 进程,

    child = pexpect.spawn("/path/to/parent/dir/script.sh")  # wont works for my script
    

    如果有提到script.sh 的相对路径,这将不起作用,因为cwd(当前工作目录)是python 脚本的cwd。在我的情况下,script.sh 需要它存在的目录中的资源,

    所以为了执行它,

    child = pexpect.spawn("/path/to/parent/dir/script.sh", cwd="/path/to/parent/dir") # works 
    

    如果您没有script.sh 的硬编码父路径,请使用os.path.dirname("<absolute path to script.sh>"),如previous answer 中所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多