【问题标题】:Why does my python program run with Powershell but not Bash? Using WSL为什么我的 python 程序使用 Powershell 而不是 Bash 运行?使用 WSL
【发布时间】:2023-01-17 19:24:39
【问题描述】:

我有一个简单的 3 行 python 程序,我正在尝试运行。它会在 Powershell 中运行,但不会在 Bash 中运行。它所做的只是打开一个文本文件并在终端中打印信息。

我正在使用 WSL。

with open('C:/Users/me/Desktop/data.txt') as a:
    content = a.read()
    print(content)

我写了“python C:/Users/me/Desktop/program.py”,当我使用 Powershell 时它在 shell 中运行。

但是,一旦我将 shell 切换到 Bash 并运行“python3 directory/program.py”,它就会显示“文件”C:/Users/me/Desktop/program.py”,第 1 行,在 open('C:/Users/ me/Desktop/data.txt') 作为:FileNotFoundError [Errno 2] 没有这样的文件或目录:'C:/Users/me/Desktop/data.txt'。

请注意,出于某种原因,我在使用 Bash 时需要输入 python3 而不是 python 才能运行我的程序,但在 Powershell 中 python 而不是 python3 可以工作。

所以我只是想知道为什么在 Bash 中找到并运行了程序,但它说找不到文本文件本身。但是 Powershell 确实找到并运行了我的程序,包括找到它读取的文本文件。

谢谢

【问题讨论】:

    标签: python bash windows-subsystem-for-linux


    【解决方案1】:

    C:/Users/me/Desktop/data.txt 不是 WSL 文件系统 afaik 中的有效路径。试试/mnt/c/Users/me/Desktop/data.txt - 或使用os.path.expanduser 让它在两个平台上工作:

    import os
    filename=os.path.expanduser('~') + '/Desktop/data.txt'
    
    with open(filename) as a:
        content = a.read()
        print(content)
    

    【讨论】:

    • 哦,就是这样!非常感谢你的帮助。
    • @Redtunic 不客气!请注意,WSL 中的主目录可能与您的 Windows 主目录不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2023-01-13
    • 1970-01-01
    • 2017-05-13
    • 2021-09-10
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多