从子进程更改父进程的目录 [英] Change directory of a parent process from a child process

查看:215
本文介绍了从子进程更改父进程的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个很酷的python程序,该程序可以帮助人们以交互方式导航到其他目录.当他们到达那里时,我想让他们点击Enter并退出程序,将其保留在所选目录中.但是,您总是以与b/c中相同的目录结尾,只有python运行的子进程实际上会更改目录,而父进程的目录保持不变.

I've created a cool python program that helps people navigate to other directories in an interactive way. When they get there I'd like to have them hit Enter and exit the program leaving them in the selected dir. However, you always end up in the same dir you started in b/c only the child process that python's running in actually changes directories and the parent process' directory remains unchanged.

推荐答案

提供包装器脚本,而不是直接运行程序.程序完成后,会向包装脚本发出cd到哪个目录的信号.源包装器脚本执行cd.

Instead of running your program directly, source a wrapper script. Your program, when it completes, signals to the wrapper script what directory to cd to. The sourced wrapper script does the cd.

另一个文件浏览实用程序Midnight Commander(mc)已解决了相同的问题.这是它的包装脚本:

Another file browsing utility, Midnight Commander (mc), has addressed the same issue. Here is its wrapper script:

MC_USER=`id | sed 's/[^(]*(//;s/).*//'`
MC_PWD_FILE="${TMPDIR-/tmp}/mc-$MC_USER/mc.pwd.$$"
/usr/bin/mc -P "$MC_PWD_FILE" "$@"

if test -r "$MC_PWD_FILE"; then
        MC_PWD="`cat "$MC_PWD_FILE"`"
        if test -n "$MC_PWD" && test -d "$MC_PWD"; then
                cd "$MC_PWD"
        fi
        unset MC_PWD
fi

rm -f "$MC_PWD_FILE"
unset MC_PWD_FILE

如您所见,它定义了一个临时文件,并使用-P选项将该文件名传递给mc.在mc退出之前,它将所选目录写入该临时文件.该脚本将该临时文件和cd读取到所选目录.

As you can see, this defines a temporary file and passes that file name to mc with the -P option. Before mc is exits, it writes the chosen directory to that temporary file. This scripts reads that temporary file and cd's to the chosen directory.

为了便于运行此包装脚本,创建了一个shell别名:

To make it convenient to run this wrapper script, one creates a shell alias:

alias mc=". /usr/lib/mc/bin/mc-wrapper.sh"'

稍加修改,我希望您可以使用您的程序来完成这项工作.

With slight modifications, I expect that you can make this work with your program.

这篇关于从子进程更改父进程的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆