![](/img/trans.png)
[英]Run shell script with additional parameters from python and get output as python variable (API authentication)
[英]Unable to get output of shell script run from python
我想使用不同的路径作为参数多次运行脚本,然后查看输出。
如果我在命令提示符下使用参数path_to_code/code1.cpp
运行脚本path/lizard
path/lizard path_to_code/code1.cpp
我得到输出-我想在多个文件上运行此脚本。
看着这个和类似的问题,我尝试了
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)
无输出。
(当然,我想递归遍历目录,但这是下一步)。
如何从脚本运行的程序获取输出? 从逻辑上来说,我认为这两个版本都应该为我提供输出...我在做什么错?
尝试使用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)
从我看来,您忘记了在此过程中进行沟通。 尝试
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = p.communicate()
return iter(stdout, b'')
干杯
根据对我问题的评论,我尝试了
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.