Python - 拖放到终端作为输入? macOS -zsh
Python - Drag and drop into terminal as input? MacOS -zsh
代码示例:
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...')
我正在编写将文件路径作为输入的代码。如果我 copy/paste 进入终端的路径有效,但当我将文件拖放到终端 window 中时无效。我认为这是因为终端转义了路径名中的空格,所以 input() 返回的字符串最终指向一个不存在的目录。
万一我解释的不好:
路径:'/Downloads/Kappa - 芥川Ryuunosuke.txt'
变成:'/Downloads/Kappa\ \ -\ Akutagawa\ \ Ryuunosuke.txt' 如果我将文件拖到终端 window。其中,作为一个字符串,没有指向任何内容。
有没有办法关闭终端的自动转义行为?或者更好的方法来编写这段代码?
对于这个特定的工作流程,我更喜欢拖放,所以我不介意某个解决方案是否会破坏手动输入路径的能力。
谢谢。
您可以轻松取消转义路径:
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
代码示例:
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...')
我正在编写将文件路径作为输入的代码。如果我 copy/paste 进入终端的路径有效,但当我将文件拖放到终端 window 中时无效。我认为这是因为终端转义了路径名中的空格,所以 input() 返回的字符串最终指向一个不存在的目录。
万一我解释的不好:
路径:'/Downloads/Kappa - 芥川Ryuunosuke.txt'
变成:'/Downloads/Kappa\ \ -\ Akutagawa\ \ Ryuunosuke.txt' 如果我将文件拖到终端 window。其中,作为一个字符串,没有指向任何内容。
有没有办法关闭终端的自动转义行为?或者更好的方法来编写这段代码?
对于这个特定的工作流程,我更喜欢拖放,所以我不介意某个解决方案是否会破坏手动输入路径的能力。
谢谢。
您可以轻松取消转义路径:
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