子进程popen不执行命令

时间:2016-12-13 10:10:57

标签: python-2.7

我在一个文件中有一组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)

1 个答案:

答案 0 :(得分:1)

您可以使用os.systemsubprocess.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已弃用但仍可使用