簡體   English   中英

python3 chdir()似乎不起作用

[英]python3 chdir() does not seem to work

作為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()

問題不在於Python,而是問題在於您試圖做的事情是不可能的。

當您啟動Python解釋器(腳本或交互式REPL)時,您是從“外殼”(Bash等)開始的。 該外殼程序具有一些工作目錄,並且它在同一目錄中啟動Python。 當Python更改其自己的工作目錄時,它不會影響父外殼程序,也不會在啟動后影響外殼程序工作目錄中的Python。

如果要編寫一個程序來更改Shell中的目錄,則應在Shell本身中定義一個函數。 該函數可以調用Python來確定要更改的目錄,例如,如果myscript.py打印要切換到的目錄,則shell函數可以只是cd $(~/myscript.py)

這是@ephemient的C解決方案的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())'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM