【问题标题】:Python - Drag and drop into terminal as input? MacOS -zshPython - 拖放到终端作为输入? macOS -zsh
【发布时间】:2020-09-27 22:45:37
【问题描述】:

代码示例:

from pathlib import Path
myfile =input('Enter the absolute path or drag a file into the terminal:')
myfileStripped= Path(myfile).read_text().replace('\n','').replace(' ','').split('。')
print('Stripping file...????')

我正在编写将文件路径作为输入的代码。如果我将路径复制/粘贴到终端中,它会起作用,但当我将文件拖放到终端窗口中时则不起作用。我认为这是因为终端转义了路径名中的空格,所以 input() 返回的字符串最终指向一个不存在的目录。

如果我没有做好解释工作:

路径:'/Downloads/Kappa - Akutagawa Ryuunosuke.txt'

如果我将文件拖到终端窗口中,则变为:'/Downloads/Kappa\ -\ Akutagawa\ \ Ryuunosuke.txt'。其中,作为一个字符串,什么都没有。

有没有办法关闭终端的自动转义行为?还是编写此代码的更好方法?

对于这个特定的工作流程,我更喜欢拖放操作,因此我不介意解决方案是否会破坏手动输入路径的能力。

谢谢。

【问题讨论】:

  • 什么操作系统,哪个终端?
  • (一般来说,转义空格是正确的做法。要么这样,要么引用整个事情。)
  • 更新--- macOS 和 zsh?
  • 为什么不直接取消转义? myfile = '/private/tmp/3\\ 522.dat '.replace('\\ ', ' ').strip().

标签: python python-3.x input terminal command-line-arguments


【解决方案1】:

您可以轻松地取消路径:

myfile =input('Enter the absolute path or drag a file into the terminal:')
Enter the absolute path or drag a file into the terminal:/private/tmp/3\ 522.dat
print(myfile)
myfile = myfile.replace('\\ ', ' ').strip()
os.path.exists(myfile)

输出:

/private/tmp/3 522.dat
True

【讨论】:

  • 哇,谢谢你,巫师!这个想法出现了,但我被卡住了,因为我没有意识到/记得变量可以重新分配哈哈。再次感谢!
猜你喜欢
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
相关资源
最近更新 更多