我想多次运行一个脚本,使用不同的路径作为参数,并查看输出。
如果我在命令提示符
中运行带有参数path/lizard
的脚本path_to_code/code1.cpp
path/lizard path_to_code/code1.cpp
我得到输出 - 我想在多个文件上运行此脚本。
查看this和类似问题,我试过了
import os, glob
def run_command(command):
os.system(command)
program = '"C:/Python27/Scripts/lizard.bat "'
path = '"path_to_code/*.cpp"'
for path1 in glob.glob(path):
command = program + path1
run_command(command)
没有输出。
import glob, subprocess
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = p.communicate()
print out
program = '"C:/Python27/Scripts/lizard.bat "'
path = '"path_to_code/*.cpp"'
for path1 in glob.glob(path):
command = program + path1
run_command(command)
没有输出。
(当然我想通过目录递归迭代,但这是下一步)。
如何从脚本中获取程序的输出?我认为逻辑上两个版本都应该让我得到输出......我做错了什么?
答案 0 :(得分:1)
尝试使用subprocess.check_output
它应该做你想要的。
[~] cat foo.sh
#!/bin/sh
echo "Hello World!"
[~] python2.7
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> foo = subprocess.check_output('./foo.sh')
>>> foo
'Hello World!\n'
>>>
所以在你的具体例子中
def run_command(command):
return subprocess.check_output(command,stderr=subprocess.STDOUT)
答案 1 :(得分:1)
从我看到的你忘了打电话沟通的过程。尝试
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = p.communicate()
return iter(stdout, b'')
干杯
答案 2 :(得分:0)
根据我的问题的评论,我试过
program = 'C:/Python27/Scripts/lizard.bat'
...
command = [program, path1]
工作 - 然后我意识到报价是问题,Etan Reisner是正确的。消除它们使它成功。
完整更正的代码:
import os, subprocess, fnmatch
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = p.communicate()
print out
program = 'C:/Python27/Scripts/lizard.bat'
path = 'path_to_code'
matches = []
for root, dirs, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, '*.cpp'):
matches.append(os.path.join(root, filename))
for path1 in matches:
command = [program, path1]
run_command(command)