[英]Python: Get current working directory from terminal
Hello I'm writing a small script which will make a webbsite template for me.您好,我正在编写一个小脚本,它将为我制作一个网站模板。 I'm going to make an alias which would run the script and thats why I have a problem.
我将创建一个别名来运行脚本,这就是我遇到问题的原因。 When running the script, I don't want to write a directory to where I want to create my folder.
运行脚本时,我不想将目录写入要创建文件夹的位置。 I want it to create in my terminals working directory.
我希望它在我的终端工作目录中创建。 How do I "os.chdir()" to my terminals working directory.
我如何“os.chdir()”到我的终端工作目录。 I have tried:
我试过了:
import os
dir_path = os.system("pwd | clip")
os.chdir(dir_path)
Output:
TypeError: chdir: path should be string, bytes or os.PathLike, not int
TL,DR I want to get the path from where in terminal the script executes and then os.chdir() to it TL,DR 我想从终端中脚本执行的位置获取路径,然后os.chdir()到它
Get current working dir:获取当前工作目录:
import os
cwd = os.getcwd()
Get the dir of the file you are executing from:获取您正在执行的文件的目录:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
You can manipulate the string with eg dir_path = os.path.join(dir_path, '..', 'somefolder')
.您可以使用例如
dir_path = os.path.join(dir_path, '..', 'somefolder')
操作字符串。
With the resulting string you can do os.chdir(dir_path)
使用结果字符串,您可以执行
os.chdir(dir_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.