【问题标题】:how to pass python variable in os.system or subprocess?如何在 os.system 或子进程中传递 python 变量?
【发布时间】:2021-06-10 07:18:00
【问题描述】:

我有一个 python 函数,它使用随机库生成随机字符串并将其分配给 python 中的变量我想在os.system 命令中使用它

os.system("mysql -u root --password=variable here < /tmp/db.setup")

如何做到这一点?

【问题讨论】:

    标签: python linux shell scripting os.system


    【解决方案1】:

    使用f-string

    os.system(f"mysql -u root --password={variable_name} < /tmp/db.setup")
    

    【讨论】:

      【解决方案2】:

      字符串插值或 f 字符串(与我同时提供的其他答案):

      os.system("mysql -u root --password=$'%s' < /tmp/db.setup" % (password,))
      

      我会将它包装在一个函数中,以便您传入变量。如果您的密码包含任何 shell 魔法,如 !、?、* 等,那么您需要引用它(就像我一样)。如果您的密码包含 ' 您需要用 ' 引用它。

      使用 mysql 模块而不是 os.system。

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 2011-11-05
        • 1970-01-01
        • 2012-09-26
        • 2021-06-13
        • 2014-04-01
        • 1970-01-01
        • 2013-03-06
        • 2018-12-17
        相关资源
        最近更新 更多