将终端命令转换为python脚本

时间:2015-12-19 05:32:39

标签: python

如何将此终端命令转换为python? 这是我尝试过的代码,我需要一些帮助。我要传入的值是< | grep“http”>包括文件本身,但传递多个值时出错。

终端命令:     swfdump -a /home/cfc/swf/swf/flash2.swf | grep 'http'

尝试1:     dump = Popen(["swfdump", "-a", filename, "|", "grep", "'http'"])

尝试2:     dump = check_output(["swfdump", "-a", filename , "| grep 'http'"])

错误:

尝试1:

Only one file allowed. You supplied at least two. (/home/cfc/swf/swf/flash2.swf and |)
Only one file allowed. You supplied at least two. (| and grep)
Only one file allowed. You supplied at least two. (grep and 'http')
Couldn't open 'http': No such file or directory
Only one file allowed. You supplied at least two. (/home/cfc/swf/swf/flash2.swf and |)
Only one file allowed. You supplied at least two. (| and grep)
Only one file allowed. You supplied at least two. (grep and 'http')
Couldn't open 'http': No such file or directory

尝试2:

Only one file allowed. You supplied at least two. (/home/cfc/swf/swf/flash2.swf and | grep 'http')
Couldn't open | grep 'http': No such file or directory
Traceback (most recent call last):
File "./SWFFile.py", line 62, in <module>
main()
File "./SWFFile.py", line 61, in main
trid()
File "./SWFFile.py", line 34, in trid
swfDump()
File "./SWFFile.py", line 48, in swfDump
dump = check_output(["swfdump", "-a", filename , "| grep 'http'"] )
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['swfdump', '-a', '/home/cfc/swf/swf/flash2.swf', "| grep 'http'"]' returned non-zero exit status 1

2 个答案:

答案 0 :(得分:1)

管道命令"|"是一个shell构造,对python没有意义。当您使用列表并且没有Popen执行shell=True时,将绕过shell,并且管道符号将作为命令行参数传递给正在执行的程序。困惑的程序会回报错误。

您可以通过将命令转换为字符串或让python将命令转换为字符串来运行shell:

dump = Popen("swfdump -a {} | grep 'http'".format(filename),
     shell=True)

dump = Popen(subprocess.list2cmdline(
    ["swfdump", "-a", filename, "|", "grep", "'http'"]),
    shell=True)

或者,在python本身进行搜索

proc = Popen(["swfdump", "-a", filename], stdout=subprocess.PIPE)
for line in proc.stdout:
    if 'http' in line:
        print(line.strip())
proc.wait()

答案 1 :(得分:1)

如果您对从Python运行大量外部命令感兴趣,使用sh module可以使结果更简单,更易读:

from sh import swfdump, grep

grep(swfdump('-a', '/home/cfc/swf/swf/flash2.swf'), 'http')

请注意,使用Python比使用外部命令更好地完成grepping:

from sh import swfdump

for line in swfdump('-a', '/home/cfc/swf/swf/flash2.swf').split('\n'):
    if 'http' in line:
        print(line)