如何在 os.system 或子进程中传递 python 变量?
how to pass python variable in os.system or subprocess?
我有一个 python 函数,它使用随机库生成随机字符串并将其分配给 python 中的一个变量 我想在 os.system
命令中使用它,如
os.system("mysql -u root --password=variable here < /tmp/db.setup")
如何实现?
使用f-string
os.system(f"mysql -u root --password={variable_name} < /tmp/db.setup")
字符串插值或 f 字符串(与我同时提供的其他答案):
os.system("mysql -u root --password=$'%s' < /tmp/db.setup" % (password,))
我会将其包装在一个函数中,以便您传入变量。如果您的密码包含任何 shell 魔术,如 !、?、* 等,那么您需要引用它(就像我一样)。如果您的密码包含 ' 您需要用 '.
引号
使用 mysql 模块代替 os.system。
我有一个 python 函数,它使用随机库生成随机字符串并将其分配给 python 中的一个变量 我想在 os.system
命令中使用它,如
os.system("mysql -u root --password=variable here < /tmp/db.setup")
如何实现?
使用f-string
os.system(f"mysql -u root --password={variable_name} < /tmp/db.setup")
字符串插值或 f 字符串(与我同时提供的其他答案):
os.system("mysql -u root --password=$'%s' < /tmp/db.setup" % (password,))
我会将其包装在一个函数中,以便您传入变量。如果您的密码包含任何 shell 魔术,如 !、?、* 等,那么您需要引用它(就像我一样)。如果您的密码包含 ' 您需要用 '.
引号使用 mysql 模块代替 os.system。