gpt4 book ai didi

python - 从脚本内更改目录后如何返回脚本目录?

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:47 25 4
gpt4 key购买 nike

我正在更改函数内的目录,但无法返回到脚本所在的目录。

我尝试使用 __FILE__sys.argv[0] 来相应地获取文件和目录的名称,但这没有帮助。

#!/usr/bin/env python3
import time
import sys, os

script = sys.argv[0]
script_path = os.path.dirname(script)

def fun1():

abspath = os.path.abspath(__file__)
print('abspath = {}'.format(abspath))
print('file = {}'.format(sys.argv[0]))
print('__file__ = {}'.format(__file__))
dname = os.path.dirname(abspath)
print('dname = {}'.format(dname))
os.chdir(dname)
print('CWD - fun1() = {}'.format(os.getcwd()))

def fun2():
cwd = os.getcwd()
if cwd != '/xyz/testdir':
os.chdir("/xyz/testdir")
print('CWD - fun2() = {}'.format(os.getcwd()))

def main():

while True:
print('Entering fun1()')
fun1()
print('Entering fun2()')
fun2()
print('Sleeping for 5 secs')
time.sleep(5)
print()

if __name__ == "__main__":
main()

实际结果 -

Entering fun1()
abspath = /abc/chdir.py
file = chdir.py
__file__ = chdir.py
dname = /abc
CWD - fun1() = /abc
Entering fun2()
CWD - fun2() = /xyz/testdir
Sleeping for 5 secs

Entering fun1()
abspath = /xyz/testdir/chdir.py
file = chdir.py
__file__ = chdir.py
dname = /xyz/testdir
CWD - fun1() = /xyz/testdir
Entering fun2()
CWD - fun2() = /xyz/testdir
Sleeping for 5 secs

预期结果 -

Entering fun1()
abspath = /abc/chdir.py
file = chdir.py
__file__ = chdir.py
dname = /abc
CWD - fun1() = /abc
Entering fun2()
CWD - fun2() = /xyz/testdir
Sleeping for 5 secs

Entering fun1()
abspath = /abc/chdir.py
file = chdir.py
__file__ = chdir.py
dname = /abc
CWD - fun1() = /abc
Entering fun2()
CWD - fun2() = /xyz/testdir
Sleeping for 5 secs

即在第二次(以及后续迭代)期间,脚本应返回到原始目录。提前致谢。

最佳答案

根据我的理解,您希望第二次迭代中的函数 1 中的工作目录与第一次迭代中的工作目录相同。因此,函数 1 将使用脚本目录返回始终相同的工作目录。

import time
import sys, os
script = sys.argv[0]
ab_path = os.path.abspath(__file__)
s_directory=os.path.dirname(ab_path)

def fun1():
abspath = os.path.abspath(__file__)
print ('script path =================={}',s_directory)
print('abspath = {}'.format(abspath))
print('file = {}'.format(sys.argv[0]))
print('__file__ = {}'.format(__file__))
print('dname = {}'.format(s_directory))
os.chdir(s_directory)
print('CWD - fun1() = {}'.format(os.getcwd()))
print('**************************************fun1*******************************')

def fun2():
cwd = os.getcwd()
if cwd != '/home/test/testdir':
os.chdir("/home/test/testdir")
print('CWD - fun2() = {}'.format(os.getcwd()))
print('**************************************fun2*******************************')

def main():
while True:
print('Entering fun1()')
fun1()
print('Entering fun2()')
fun2()
print('Sleeping for 5 secs')
time.sleep(5)
print()

if __name__ == "__main__":
main()

关于python - 从脚本内更改目录后如何返回脚本目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57238161/

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