我在一个文件中有一组linux命令,我试图在python脚本中逐个执行它们
for line in file:
p = subprocess.Popen(line,shell=True,stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
上面的行没有执行任何命令,因为我看不到任何输出。 如果只显式提供了命令,那么它就会被执行
cmd = "date"
p = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
答案 0 :(得分:1)
您可以使用os.system
或subprocess.call
完整代码:
import os
with open("/path/to/file") as file:
command = file.readlines()
for line in command:
p = str(os.system(str(line)))
语法是
import os
os.system("path/to/executable option parameter")
或
os.system("executable option paramter")
例如,
os.system("ls -al /home")
或部分代码(使用subprocess
):
for line in file:
subprocess.call(line, shell=True)
我在https://docs.python.org/2/library/subprocess.html
收到了此信息注意:os.system
已弃用但仍可使用