python3 chdir()似乎不起作用

时间:2015-01-19 23:20:53

标签: python python-3.x chdir

作为python的新手,我想我会编写一个小python3脚本来帮助我在命令行上切换目录(ubuntu trusty)。不幸的是os.chdir()似乎不起作用。 我尝试过以各种方式修补它,例如在路径周围放置引号,删除前导斜线(显然不起作用),甚至只是硬编码,但我无法将其转换为工作 - 谁能告诉我我在这里失踪了什么?

chdir()的调用即将结束 - 您也可以在github中看到代码

#!/usr/bin/env python3
# @python3
# @author sabot <sabot@inuits.eu>
"""Switch directories without wearing out your slash key"""
import sys
import os
import json
import click

__VERSION__ = '0.0.1'

# 3 params are needed for click callback
def show_version(ctx, param, value):
    """Print version information and exit."""
    if not value:
        return
    click.echo('Goto %s' % __VERSION__)
    ctx.exit() # quit the program

def add_entry(dictionary, filepath, path, alias):
    """Add a new path alias."""
    print("Adding alias {} for path {} ".format(alias,path))
    dictionary[alias] = path

    try:
        jsondata = json.dumps(dictionary, sort_keys=True)
        fd = open(filepath, 'w')
        fd.write(jsondata)
        fd.close()
    except Exception as e:
        print('Error writing to dictionary file: ', str(e))
        pass

def get_entries(filename):
    """Get the alias entries in json."""
    returndata = {}
    if os.path.exists(filename) and os.path.getsize(filename) > 0:
        try:
            fd = open(filename, 'r')
            entries = fd.read()
            fd.close()
            returndata = json.loads(entries)

        except Exception as e:
            print('Error reading dictionary file: ', str(e))
            pass
    else:
        print('Dictionary file not found or empty- spawning new one in', filename)
        newfile = open(filename,'w')
        newfile.write('')
        newfile.close()

    return returndata

@click.command()
@click.option('--version', '-v', is_flag=True, is_eager=True,
              help='Print version information and exit.', expose_value=False,
              callback=show_version)
@click.option('--add', '-a', help="Add a new path alias")
@click.option('--target', '-t', help="Alias target path instead of the current directory")
@click.argument('alias', default='currentdir')
@click.pass_context
def goto(ctx, add, alias, target):
    '''Go to any directory in your filesystem''' 

    # load dictionary
    filepath = os.path.join(os.getenv('HOME'), '.g2dict')
    dictionary = get_entries(filepath)

    # add a path alias to the dictionary
    if add:
        if target: # don't use current dir as target
            if not os.path.exists(target):
                print('Target path not found!')
                ctx.exit()
            else:
                add_entry(dictionary, filepath, target, add)
        else: # use current dir as target
            current_dir = os.getcwd()
            add_entry(dictionary, filepath, current_dir, add)

    elif alias != 'currentdir':
        if alias in dictionary:
            entry = dictionary[alias]
            print('jumping to',entry)
            os.chdir(entry)
        elif alias == 'hell':
            print("Could not locate C:\Documents and settings")
        else:
            print("Alias not found in dictionary - did you forget to add it?")

if __name__ == '__main__':
    goto()

2 个答案:

答案 0 :(得分:1)

问题不在于Python,问题在于您尝试做的事情是不可能的。

当你启动Python解释器(脚本或交互式REPL)时,你可以从你的&#34; shell&#34; (Bash等)。 shell有一些工作目录,它在同一个目录中启动Python。当Python更改自己的工作目录时,它不会影响父shell,shell的工作目录中的更改也不会影响Python的启动。

如果要编写一个更改shell中目录的程序,则应在shell中定义一个函数。该函数可以调用Python来确定要更改的目录,例如如果cd $(~/myscript.py)打印出要切换到的目录,则shell函数可以只是myscript.py

答案 1 :(得分:0)

这是{3}}的Python 3版本:

#!/usr/bin/env python3
"""Change parent working directory."""
#XXX DIRTY HACK, DO NOT DO IT
import os
import sys
from subprocess import Popen, PIPE, DEVNULL, STDOUT

gdb_cmd = 'call chdir("{dir}")\ndetach\nquit\n'.format(dir=sys.argv[1])
with Popen(["gdb", "-p", str(os.getppid()), '-q'],
           stdin=PIPE, stdout=DEVNULL, stderr=STDOUT) as p:
    p.communicate(os.fsencode(gdb_cmd))
sys.exit(p.wait())

示例:

# python3 cd.py /usr/lib && python3 -c 'import os; print(os.getcwd())'