我在一个文件中有一组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)发布于 2016-12-13 12:40:04
您可以使用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是不推荐的,但仍然有效。
发布于 2022-01-24 22:04:46
删除shell=True之后,当我执行以下命令时,我的命令也面临相同的问题:
subprocess.Popen(
["python3", os.path.join(script_dir, script_name)] + list(args),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=script_dir,
shell=True
)但一旦我取下外壳,它就正常工作了。
https://stackoverflow.com/questions/41118451
复制相似问题