【问题标题】:How do I use multiple variables and strings within an os.system() command?如何在 os.system() 命令中使用多个变量和字符串?
【发布时间】:2022-10-05 16:19:52
【问题描述】:

我试图制作一个下载文件的简单程序。我的命令部分有问题。这是代码:

import os

#gather user input
print(\"hello! welcome to the website dowloader! paste in the url(including the http 
part) and type in the file name!)\")
url = input(\"website url: \")
filename = input(\"the filename:\")

#the command i want run. for example, if the url was \"https://example.com\" and the 
#filename was \"example.html\"
#then i would want the command run to be: \'curl https://example.com --output 
#example.html\'
cmd = str(\"curl \", url,\" --output \", filename)
os.system(cmd)
  • str(\"curl \", url,\" --output \", filename) 你在问如何连接字符串吗?您可以使用+ 运算符来执行此操作,但通常在这里格式化字符串会更容易,所以只需f\"curl {url} --output {filename}\"。此外,您可能应该使用subprocess 而不是os.system
  • 而且,你为什么不直接使用 Python 下载文件而不是使用 curl 呢?
  • 我知道,我是在指出这一点,试图弄清楚你是什么意思是通过那个。这显然是不正确的,因为它会引发错误(顺便说一句,可能应该在此处发布该错误)
  • {} 用于将变量放入命令中吗?
  • 没有“命令”。这是一个.它为字符串格式化,是的,它会进行字符串插值

标签: python curl os.system


【解决方案1】:

str("curl ", url," --output ", filename) 你在问如何连接字符串吗?您可以使用 + 运算符来执行此操作,但通常在这里格式化字符串会更容易,所以只需 f"curl {url} --output {filename}"。此外,您可能应该使用subprocess 而不是os.system

由@juanpa.arrivillaga 回答

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 2018-12-08
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多