将变量从 python 3.8 传递到 shell 命令
Passign a variable from python 3.8 to a shell command
如何将变量从 python 循环传递到同一 python 脚本中的 shell 命令?
例如
假设 textfile.txt 有一个主机名列表
import subprocess
with open("textfile.txt") as f:
for i in f:
if 'server01' in i:
subprocess.run(["scp", "user@<value-of-i>:/path-to-file", "path-to-save"])
那么当 if 命令为真时,我如何将 i 的值传递给该 scp 命令?
非常感谢
像这样:
subprocess.run(["scp", "user@{}:/path-to-file".format(i), "path-to-save"])
您可以使用 f-strings:
subprocess.run(["scp", f"user@{i.strip()}:/path-to-file", "path-to-save"])
请注意,像这样将字符串传递到命令行可能是不安全的,这取决于您是否相信 textfile.txt
的内容是安全的。
此外,您需要删除空格,因为循环遍历行会留下换行符。
您可以按照通常的方式传递它 string-formatting。
str.format:
if 'server01' in i:
subprocess.run(["scp", "user@{}:/path-to-file".format(i), "path-to-save"])
f-strings:
if 'server01' in i:
subprocess.run(["scp", f"user@{i}:/path-to-file", "path-to-save"])
百分比:
if 'server01' in i:
subprocess.run(["scp", "user@%s:/path-to-file" % i, "path-to-save"])
字符串连接:
if 'server01' in i:
subprocess.run(["scp", "user@" + i + ":/path-to-file", "path-to-save"])
如何将变量从 python 循环传递到同一 python 脚本中的 shell 命令?
例如 假设 textfile.txt 有一个主机名列表
import subprocess
with open("textfile.txt") as f:
for i in f:
if 'server01' in i:
subprocess.run(["scp", "user@<value-of-i>:/path-to-file", "path-to-save"])
那么当 if 命令为真时,我如何将 i 的值传递给该 scp 命令?
非常感谢
像这样:
subprocess.run(["scp", "user@{}:/path-to-file".format(i), "path-to-save"])
您可以使用 f-strings:
subprocess.run(["scp", f"user@{i.strip()}:/path-to-file", "path-to-save"])
请注意,像这样将字符串传递到命令行可能是不安全的,这取决于您是否相信 textfile.txt
的内容是安全的。
此外,您需要删除空格,因为循环遍历行会留下换行符。
您可以按照通常的方式传递它 string-formatting。
str.format:
if 'server01' in i:
subprocess.run(["scp", "user@{}:/path-to-file".format(i), "path-to-save"])
f-strings:
if 'server01' in i:
subprocess.run(["scp", f"user@{i}:/path-to-file", "path-to-save"])
百分比:
if 'server01' in i:
subprocess.run(["scp", "user@%s:/path-to-file" % i, "path-to-save"])
字符串连接:
if 'server01' in i:
subprocess.run(["scp", "user@" + i + ":/path-to-file", "path-to-save"])