简体   繁体   English

如何测试当前目录是否为 $HOME?

[英]How to test if current directory is $HOME?

I am converting a shell script into a Python script and having some trouble with testing an IF condition.我正在将 shell 脚本转换为 Python 脚本,并且在测试 IF 条件时遇到了一些问题。 In this environment we are running Python 3.9.2.在此环境中,我们正在运行 Python 3.9.2。

I originally set 2 variables (homeDir and curDir), create an if-else condition to test if the variables are equal.我最初设置了 2 个变量(homeDir 和 curDir),创建一个 if-else 条件来测试变量是否相等。

Running the script I do a cd to the $HOME directory and run the Python script.运行脚本我 cd 到 $HOME 目录并运行 Python 脚本。

It always prints "False", even when the console output shows the variables are equal.它总是打印“False”,即使控制台 output 显示变量相等。

I am expecting the script to return "Take Action ABC" when running the script in the $HOME directory.在 $HOME 目录中运行脚本时,我希望脚本返回“Take Action ABC”。

Screen capture showing the output:显示 output 的屏幕截图:
在此处输入图像描述

Sample of the code:代码示例:

import os
from pathlib import Path

homeDir = Path.home()
curDir = os.getcwd()

print('DEBUG homeDir:', homeDir)
print('DEBUG curDir:', curDir)

if curDir == homeDir:
    print('True')
else:
    print('False')

You have objects of different types;你有不同类型的对象; homeDir is a Path object, while curDir is a str . homeDir是一个Path object,而curDir是一个str For that reason they won't compare equal, even if semantically they are the same path.因此,即使在语义上它们是相同的路径,它们也不会比较相等。 Use one module or the other instead of mixing pathlib and os .使用一个或另一个模块,而不是混合pathlibos One solution would be to replace一种解决方案是更换

os.getcwd()

with

Path.cwd()

The latter is thepathlib equivalent to os.getcwd() .后者是等效于os.getcwd()pathlib

Example from a Python 3.9 REPL invoked from where my current directory is my user home directory:来自 Python 3.9 REPL 的示例从我的当前目录是我的用户主目录调用:

>>> os.getcwd() == Path.home()
False
>>> Path.cwd() == Path.home()
True

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

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