'file not found' error when running local

2019-06-21 04:47发布

I'm writing a Python program to call a local binary with Popen to capture its output. I change directories to it with os.chdir and I have verified the file is there. However, the following code raises a 'file not found' exception.

Can anyone tell me what I'm doing wrong? Is there something special I have to do with running programs from directories not in my $PATH? Thanks in advance.

try:
    os.chdir('/home/me')
    p = sub.Popen(['./exec', '--arg', 'arg1'], cwd=os.getcwd(), stdout=sub.PIPE)
    out, err = p.communicate()
    print("done")
except OSError as e:
    print("error %s" % e.strerror)

2条回答
姐就是有狂的资本
2楼-- · 2019-06-21 04:53

Note this section of the docs (emphasis mine):

If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

Try using an absolute path with Popen.

p = sub.Popen(['/home/me/exec', '--arg', 'arg1'], stdout=sub.PIPE)
查看更多
走好不送
3楼-- · 2019-06-21 05:04

To run a program from your $PATH, simply pass shell=True to Popen.

EDIT:

As well, as the OP asked, this works to run a program from the current directory.

查看更多
登录 后发表回答