Python字符串添加双引号及Windows下torrent命令双引号丢失问题
1. 如何在Python中为字符串添加双引号(")?
给字符串加双引号其实有好几种简单实用的方法,挑顺手的用就行:
- 直接拼接字符串:新手也能快速上手,把双引号和目标字符串直接连起来:
my_str = "hello" quoted_str = '"' + my_str + '"' print(quoted_str) # 输出结果:"hello" - 用f-string格式化(Python 3.6及以上版本推荐):写法直观清爽,可读性拉满:
my_str = "hello" quoted_str = f'"{my_str}"' print(quoted_str) # 输出结果:"hello" - str.format()方法:兼容性超强,老版本Python也能放心用:
my_str = "hello" quoted_str = '"{}"'.format(my_str) print(quoted_str) # 输出结果:"hello" - 转义双引号包裹:如果字符串本身不含双引号,直接在定义时用转义的双引号把内容包起来:
quoted_str = "\"hello\"" print(quoted_str) # 输出结果:"hello"
2. 解决Windows命令提示符执行torrent命令时双引号丢失的问题
你遇到的这个问题,本质是Windows命令解析器对引号的处理规则比较“挑剔”——直接拼接的引号会被解析掉,导致磁链被拆成零散参数,所以才会报类似'dn' is not recognized的错误。给你几个靠谱的解决办法:
方案1:调整引号的转义方式
用三重引号把整个命令包起来,内部的双引号就能正常被识别了:
import os link = "magnet:?xt=urn:btih:abcdef123456..." os.system(f"""start /wait cmd /c torrent "{link}" """)
或者用单引号包裹整个命令,内部用双引号包磁链:
os.system('start /wait cmd /c torrent "' + link + '"')
方案2:用subprocess模块替代os.system(更推荐)
Python官方早就不推荐用os.system了,subprocess对命令参数的处理更可靠,还能避免很多手动转义的麻烦:
import subprocess link = "magnet:?xt=urn:btih:abcdef123456..." # 如果torrent已经在系统PATH里,直接这么写就行 subprocess.run(["torrent", link], shell=True, check=True) # 要是必须通过cmd启动并等待完成,改成这样: subprocess.run(["cmd", "/c", "torrent", link], shell=True, check=True)
如果一定要保留start /wait的逻辑,需要对引号做双层转义(因为shell会解析一次,得加两层反斜杠):
subprocess.run('start /wait cmd /c "torrent \\"{}\\""'.format(link), shell=True)
方案3:写临时bat文件执行
要是上面的方法都不好使,还有个笨但有效的办法——把命令写到临时bat文件里再执行:
import os link = "magnet:?xt=urn:btih:abcdef123456..." # 写入临时bat文件 with open("run_torrent.bat", "w") as f: f.write(f'torrent "{link}"') # 执行bat文件 os.system("start /wait cmd /c run_torrent.bat") # 执行完记得删掉临时文件 os.remove("run_torrent.bat")
内容的提问来源于stack exchange,提问作者Daquaney
相关产品推荐
相关产品推荐

