简体   繁体   English

在 Python 中更改调用者的当前工作目录

[英]Change caller's current working directory in Python

I'm writing a simple script which ideally will help me conveniently change directories around my system.我正在编写一个简单的脚本,理想情况下,它可以帮助我方便地更改系统周围的目录。

The details of the implementation don't matter, but let's say ideally I will place this script in /usr/bin and call it with an argument denoting where I want to go to on the system: goto project1实现的细节无关紧要,但假设理想情况下我会将这个脚本放在/usr/bin ,并使用一个参数来调用它,该参数表示我想去系统上的位置: goto project1

I would expect that when the script exits, my terminal's current working would have changed to that of Project 1.我希望当脚本退出时,我终端的当前工作会更改为项目 1 的工作。

In order to accomplish this, I tried:为了实现这一点,我尝试了:

os.chdir('/')

subprocess.call('cd /', shell=True)

Neither of which work.两者都不起作用。 The first changes the working directory in Python and the second spawns a shell at / .第一个更改 Python 中的工作目录,第二个在/处生成一个 shell。

Then I realized how naive I was being.然后我意识到我是多么天真。 When a program is run, the terminal is just forking a process, while reading from stdout, which my program is writing to.当程序运行时,终端只是分叉一个进程,同时从我的程序写入的标准输出中读取。 Whatever it does, it wouldn't affect the state of terminal.无论它做什么,它都不会影响终端的状态。

But then I thought "I've been using cd for years, surely someone wrote code for that", thinking there might be something to go off of (system call or something?).但后来我想“我已经使用cd多年了,肯定有人为此编写了代码”,认为可能会有一些事情要处理(系统调用或其他什么?)。

But cd is not even coreutils .但是cd甚至不是coreutils Instead, the source of cd is this:相反, cd的来源是这样的:

builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

So, a couple of questions come to mind:所以,想到了几个问题:

  • What's actually going on behind the scenes when a user calls cd ?当用户调用cd时,幕后到底发生了什么? (Meaning, how is the terminal and the system actually interacting?) (意思是,终端和系统实际上是如何交互的?)
  • Is it possible to have something like a Python script alter the terminal location?是否有可能让 Python 脚本之类的东西改变终端位置?

Thanks so much for your help!非常感谢你的帮助!

You could do it as a pair of scripts:您可以将其作为一对脚本来执行:

directory.py目录.py

#!/usr/bin/python

import sys

directory =  sys.argv[1]

# do something interesting to manipulate directory...

print directory + "tmp"

directory.csh目录.csh

#!/bin/csh -f

cd `python directory.py $1`

Result:结果:

> pwd
/Users/cdl
> source directory.csh "/"
> pwd
/tmp
> 

Substitute your favorite shell and variant of Python as desired.根据需要替换您最喜欢的 shell 和 Python 变体。 Turn on execute for the Python script to simplify further.为 Python 脚本打开执行以进一步简化。

Clearly the shell is changing the directory but Python can do all the clever logic you want to figure out where to send the shell.很明显,shell 正在更改目录,但 Python 可以执行您想要找出将 shell 发送到何处的所有巧妙逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM