如何从python脚本更改当前目录? [英] How do I change my current directory from a python script?

查看:146
本文介绍了如何从python脚本更改当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现自己的cd命令版本,该命令向用户提供一系列硬编码目录供您选择,并且用户必须输入与该列表中的条目相对应的数字。现在,该程序名为 my_cd.py ,应该可以有效地将用户 cd到所选目录。

I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py for now, should then effectively 'cd' the user to the chosen directory. Example of how this should work:

/some/directory
$ my_cd.py
1) ~
2) /bin/
3) /usr
Enter menu selection, or q to quit: 2

/bin
$

当前,我正在尝试使用 os.chdir('dir')进行 cd 。但是,这不起作用,可能是因为 my_cd.py 在其自己的子进程中启动了。我尝试将调用包装到名为 my_cd.sh

Currently, I'm trying to 'cd' using os.chdir('dir'). However, this doesn't work, probably because my_cd.py is kicked off in its own child process. I tried wrapping the call to my_cd.py in a sourced bash script named my_cd.sh:

#! /bin/bash
function my_cd() {
    /path/to/my_cd.py
}

/some/directory
$ . my_cd.sh
$ my_cd
... shows list of dirs, but doesn't 'cd' in the interactive shell

中 cd显示

关于如何使它工作的任何想法?

Any ideas on how I can get this to work? Is it possible to change my interactive shell's current directory from a python script?

推荐答案

这可以完成,可以通过python脚本更改我的交互式shell的当前目录吗?对工作目录的更改对父进程不可见。充其量您可以让Python脚本打印要更改的目录,然后使源脚本实际更改到该目录。

This can't be done. Changes to the working directory are not visible to parent processes. At best you could have the Python script print the directory to change to, then have the sourced script actually change to that directory.

这篇关于如何从python脚本更改当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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