gpt4 book ai didi

python3 chdir() 似乎不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:56 32 4
gpt4 key购买 nike

作为 python 的新手,我想我应该编写一个 python3 脚本来帮助我在命令行上切换目录(值得信赖的 ubuntu)。不幸的是 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)时,您可以从“shell”(Bash 等)执行此操作。 shell 有一些工作目录,并在同一目录中启动 Python。当Python更改自己的工作目录时,不会影响父shell,shell工作目录的更改也不会影响Python启动后的情况。

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

关于python3 chdir() 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035228/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com