【问题标题】:I'm having trouble marking (") in python [os.system]我在 python [os.system] 中标记 (") 时遇到问题
【发布时间】:2021-10-11 13:59:00
【问题描述】:

这是脚本

from tkinter import *
import os

window = Tk()
window.title("Download from Web")
window.geometry("300x120+200+100")

photo = PhotoImage(file = "icon/icon.png")
window.iconphoto(False, photo)


urltxt = Label(window, text = "Url").place(x = 10, y = 10)  
url = Entry(window, width=30)
url.insert(0,"")
url.grid(row=1, column=0, padx=80, pady=10)


filetxt = Label(window, text = "Save File name").place(x = 10, y = 10)  
filename = Entry(window, width=30)
filename.insert(0,".exe,.zip,.rar")
filename.grid(row=2, column=0, padx=80, pady=10)



def Message():
    os.system(f"powershell -c "Invoke-WebRequest -Uri '{url.get()}' -OutFile '{filename.get()}'"")

btnSendMessage = Button(window, text="Search", width=20, command=Message)
btnSendMessage.grid(row=4, column=0, padx=10, pady=10)

window.mainloop()

我对这部分文字有疑问

def Message():
    os.system(f"powershell -c "Invoke-WebRequest -Uri '{url.get()}' -OutFile '{filename.get()}'"")

这两个部分有问题,特别是当我将' 添加到代码中时,我得到一个错误

'{url.get()}' and '{filename.get()}'

【问题讨论】:

  • 单引号和双引号可以分别用\'\"转义
  • 你的意思是这样'\{url.get()}'
  • 一般来说,使用os.system() 是个坏主意。 subprocess 模块可以让你传递一个 argv 数组,所以你不需要弄清楚如何构造一个适当引用的字符串。
  • 另外:这适用于哪个平台? (Powershell 在 UNIX 平台上可用,所以这并不能告诉我们任何结论;但是对于 os.system 需要使用什么样的引用在 UNIX 和 Windows 之间有所不同)

标签: python os.system


【解决方案1】:

引号可以用反斜杠转义,如下所示:

os.system(f"powershell -c \"Invoke-WebRequest -Uri \'{url.get()}\' -OutFile \'{filename.get()}\'\"")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-07
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多