简体   繁体   English

如何打开当前工作目录(OS X / Linux / Win)

[英]How to open current working directory (OS X/Linux/Win)

Is there a way to open the current working directory in python? 有没有办法在python中打开当前工作目录?

current_wkd = os.getcwd()
print(current_wkd) 
.../User/Bob/folder 

Say at the end of my program, I want to open the current working directory. 在程序结束时说,我要打开当前工作目录。 I know how to open specific files, but I am interested in the "/User/Bob/folder" opening once the program is complete. 我知道如何打开特定文件,但是对程序完成后打开“ / User / Bob / folder”很感兴趣。 How to open "folder" at the end of the script? 如何在脚本末尾打开“文件夹”?

What is the best way to do this in OSX/Linux/Win. 在OSX / Linux / Win中执行此操作的最佳方法是什么。

Thank you. 谢谢。

For example, 例如,

In the terminal one can use: 在终端中,可以使用:

pwd  # get current wkd
../User/Bob/folder  
cd /User/Bob/folder  # change directory to /User/Bob/folder
open folder # To open the directory named "folder"

Is this possible as part of the python script. 这是否可能作为python脚本的一部分。 At the end, for the directory to open as in the above "open folder" command in the terminal. 最后,按照在终端中的上述“打开文件夹”命令打开目录。 I know how to find the current wkd and change it using: 我知道如何找到当前的wkd并使用以下方法进行更改:

os.getcwd()
os.chdir()

How do you open the current directory? 您如何打开当前目录? In other words, at the end of my script I want the directory/folder to open. 换句话说,在脚本的结尾,我想打开目录/文件夹。 Similarly to when opening a web browser using: 与使用以下方法打开Web浏览器类似:

webbrowser.open_new()

Thank you e9T (below) for the guidance! 谢谢e9T(下)的指导!

ANSWER: I ended up using this as part of my script at the end: 解答:最后,我最终将其用作脚本的一部分:

import subprocess 

current_directory = os.getcwd()

subprocess.check_call(['open', '--', current_directory]) # This is for OS X 

You can use subprocess to open up a file explorer for a given path. 您可以使用subprocess打开给定路径的文件浏览器。

import subprocess
import sys

def open_folder(path):
    if sys.platform == 'darwin':
        subprocess.check_call(['open', '--', path])
    elif sys.platform == 'linux2':
        subprocess.check_call(['gnome-open', '--', path])
    elif sys.platform == 'win32':
        subprocess.check_call(['explorer', path])

open_folder(path=".")  # open current directory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM