【问题标题】:python3 error when passing variable into os.chdir将变量传递到 os.chdir 时出现 python3 错误
【发布时间】:2017-04-01 09:28:13
【问题描述】:

我正在尝试找到一个特定的路径名​​并将其传递给 os.chdir,以便我可以在该目录中运行命令。我不知道确切的路径名,因此我必须运行 find 命令。我尝试了几种方法来做到这一点,每种方法都带有一个新错误。下面的代码是我尝试过的方法之一,有人可以建议最好的方法吗?或者如何解决这个错误?

源代码:

import os
import subprocess

os.system('find ~ -path "*MyDir" > MyDir.txt')

output = subprocess.check_output("cat MyDir.txt", shell=True)

os.chdir(output)

os.system("file * > MyDir/File.txt")

错误:

Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'

我知道该目录存在并假定它与 b' 和 \n' 有关。我只是不知道问题是什么。

【问题讨论】:

  • 为什么要将 find 的输出重定向到文件中,而不是直接使用 check_output 和 find?
  • 我对 python 和一般编码完全陌生。我将阅读 check_output 并尝试在我的代码中实现。感谢您让我意识到这一点。如果您能给我举个例子说明它的外观,我将不胜感激。
  • 您已经将 check_output 与 cat 一起使用,所以我很困惑您为什么不将其与 find 一起使用。
  • 哇。我已经看这个太久了,看不到我面前的东西。谢谢

标签: python python-3.x python-3.5


【解决方案1】:

strip去掉\n

output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 2016-10-14
    • 2022-01-03
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多