我正在尝试制作一个通过 Cygwin 与 RSync 交互的 Python GUI 应用程序。我已经完成了子进程,但由于路径不兼容 Unix,RSync 出现错误。
我知道路径应该格式化为
/cygdrive/<drive letter>/<path>/<to>/<file or directory>/
才能工作,这就是阻碍我的原因。我不知道如何制作以 filedialog
格式获取的路径,并且我在尝试搜索时找不到在线内容。
我尝试在路径字符串前面附加
/cygdrive/
和 os.path.join
(也许不是命令应该做的事情),但当我期望它将字符串格式化为 /cygdrive/<drive letter>/<path>/<to>/<file or directory>
时,这没有任何作用
我也尝试过使用
os.path.relpath
、os.path.normpath
并将它们直接传递给子进程命令作为 subprocess.run(["rsync", "-a" , os.path.relpath(<Source Path>)], os.path.relpath(<Destination Path>))
但也什么都没有(也可能是错误的命令,但这就是我的想法)
当前代码是这样的
import customtkinter
from tkinter import filedialog as fdiag
from tkinter import messagebox as mbox
import subprocess
import os
# Vars
global fdiagSrc, fdiagDest
fdiagDest = ''
fdiagSrc = ''
#Prepare Cygwin stuff
os.chdir(b"C:/cygwin64/bin/")
print(os.getcwd()) #Was checking if it was changing in the directory just in case
# Declare button stuff here first
def srcSel(): # Open a file dialog for Source directory selection, and assign that directory as a string to a global var
global fdiagSrc
fdiagSrc = fdiag.askdirectory()
while (len(fdiagSrc) == 0): # Show a warning in case user pressed "Cancel" or the close button on the dialog window and re-open the dialog
mbox.showwarning("Warning!", "You did not select any directory for source!")
fdiagSrc = fdiag.askdirectory()
mbox.showinfo("Src", fdiagSrc)
def destSel(): # Open a file dialog for Destination directory selection, and assign that directory as a string to a global var
global fdiagDest
fdiagDest = fdiag.askdirectory() # Show a warning in case user pressed "Cancel" or the close button on the dialog window and re-open the dialog
while (len(fdiagDest) == 0):
mbox.showwarning("Warning!", "You did not select any directory for destination!")
fdiagDest = fdiag.askdirectory()
mbox.showinfo("Dest", fdiagDest)
def GoToSendDir():
if (len(fdiagDest) == 0) or (len(fdiagSrc) == 0): # Show a warning in case they didn't select any directories
mbox.showwarning("Warning!", "You did not set any directories for Source and/or Destination! Please do that.")
else: #Proceed to transfer/mirror/clone whatever it is called
print(os.path.normpath(fdiagSrc)) # Checking the path if it is formatted properly..
subprocess.run(["rsync", " -v -a ",os.path.normpath(fdiagSrc), os.path.normpath(fdiagDest)])
[.... misc GUI stuff not related to issue ....]
很抱歉花了一些时间来关闭此问题;有点忘记了。无论如何,Michael Butscher提供的评论/答案对于我的案例来说效果很好,在我存储路径的变量上调用str.replace()
,并执行一些其他过程以使其与rsync一起使用WSL(我会使用 Cygwin,但我还没有让它与我一起工作),如下所述:
os.path.normcase(variableThatStoresPath.replace(":", "")) + "/"
variableThatStoresPath = variableThatStoresPath.replace("\\", "/")
(选择
os.path.normcase()
,因为它与 Linux 的 Windows Sybsystem 配合良好,并使用
:
替换了最常出现在类似 Windows 路径中的 F:\some\path\
,即
为 str.replace()
。选择路径我使用了 tkinter
的 filedialog.askdirectory()
方法。下一行做了更多替换,使路径更适合再次使用 str.replace()
。)我将尝试 Doug Henderson 的建议,使用 Pathlib
模块处理路径并在此处报告。