如何在python中向字符串中添加

2024-04-24 12:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在windows中启动一个torrent下载程序,它是从命令提示符执行的。它接受一个命令,比如torrent "magnet_link"。我遇到的问题是,当我使用os.system("start /wait cmd /c torrent " + '"' + link + '"')从python启动命令时,由于某种原因,字符没有显示在启动的命令提示符窗口中,这使得命令没有用。我得到的答复是:'dn' is not recognized as an internal or external command, operable program or batch file.


Tags: or命令程序cmdoswindowslink字符
2条回答

如果不转义,shell中的引号将被解释。为了避开它们,在前面加一个反斜杠。看这里:

os.system("start /wait cmd /c torrent \\\"{}\\\"".format(link))

发生了什么:

  • \\被解释为一个反斜杠
  • \"被解释为引号
  • .format(link){}替换为link,以避免添加字符串(仅用于代码样式)

Use可以使用内置的str.center

link = 'http://stackoverflow.com'
print("start /wait cmd /c torrent %s" % link.center(len(link)+2, '"'))

# start /wait cmd /c torrent "http://stackoverflow.com"

相关问题 更多 >