![](/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.