简体   繁体   English

Python:从终端获取当前工作目录

[英]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.

相关问题 从Python获取Vte(GTK Terminal Widget)的当前工作目录 - Get current working directory from Vte (GTK Terminal Widget) in Python 如何在Python中获取PowerBI的当前工作目录? - How to get Current Working Directory of PowerBI in Python? 使用 Python C 扩展获取当前工作目录 - Get Current Working Directory With Python C Extension vscode ps 或 cmd 终端不打开当前工作目录和 python 灭绝不运行工作目录 - vscode ps or cmd terminal does not open current working directory and python extinction not run working directory 从 Python 脚本获取当前目录的父目录 - Get parent of current directory from Python script Python:更改终端当前目录并调用脚本 - Python: Changing terminal current directory and calling script 使用 python cli 工具更改当前终端的目录 - Change directory of current terminal with python cli tool 如何从 Python 在 ZAEA23489CE3AA9B63406EBB28E0 终端中获取当前文本 cursor position - How to get the current text cursor position from Python in a Windows Terminal? python代码获取当前工作目录之外的文件 - python code to get the files outside the current working directory 有没有办法获取不在当前工作目录中的文件的绝对路径(在 Python 中)? - Is there a way to get an absolute path of a file which is not in the current working directory (in Python)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM