簡體   English   中英

python子進程不會運行phantomjs,但可以在linux命令行中使用

[英]python subprocess won't run phantomjs, but works in linux command line

當我在CENTOS 7服務器上運行它時,它可以從bash運行:

[myserver]$ /home/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /home/phantomjs-2.1.1-linux-x86_64/bin/thumbnails.js -3933029 91 q5975 "http://mysite/explore?viz=summary_slider"
Rendered 'http://mysite/explore?viz=summary_slider' at '/home/thumbnails/th-3933029c91q5975.png'

但是,如果我使用子進程在python中執行此操作,則會收到錯誤消息:

import subprocess
phantomjs_call = u'{0}phantomjs {0}thumbnails.js {1}'.format(phantomjspath, link)
rendered = subprocess.check_output(phantomjs_call.split())

回報

/home/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /home/phantomjs-2.1.1-linux-x86_64/bin/thumbnails.js "http://mysite/explore?viz=summary_checkbox"
Unable to render '"http://mysite/explore?viz=summary_checkbox"'

子流程參數有什么怪異的嗎? 還是外殼環境不對?

接下來,我對其進行了調整,並將完整的字符串作為一個參數傳入,然后得到OSError:

rendered = subprocess.check_output(phantomjs_call)
# didn't split this into multiple arguments
>>>[Errno 2] no such file or directory"

那個怎么樣

import subprocess
phantomjs_call = '{0}phantomjs {0}thumbnails.js {1}'.format(phantomjspath, link)
print(subprocess.check_output(phantomjs_call), shell=True)

要么

import os
phantomjs_call = '{0}phantomjs {0}thumbnails.js {1}'.format(phantomjspath, link)
print(os.system(phantomjs_call))

因此,在嘗試許多不同的變化后, subprocess ,這是與工作phantomjssubprocess32

    import subprocess32 # not the default version; this supports timeouts
    for (_id, link) in link_list:        
        phantomjs_call = u'{0}phantomjs {0}thumbnails.js {1} {2} {3} {4}'.format(phantomjspath, _id, link)
        """note: this generates a string like
/home/phantomjs-2.1.1-linux-x86_64/bin/phantomjs 
/home/phantomjs-2.1.1-linux-x86_64/bin/thumbnails.js 51514 
"http://mysite/explore?viz=summary_text"
        """
        try:
            process = subprocess32.Popen(phantomjs_call, shell=True, stdout=subprocess32.PIPE)
            # make sure phantomjs has time to download/process all the pages in the list
            # but if we get nothing after 180 sec, just move on
        except Exception as e:
            print(phantomjs_call)
            print('Popen failed', e)

        try:
            output, errors = process.communicate(timeout=180)
        except Exception as e:
            if debug == True: 
                print("\t\tException: %s" % e)
            process.kill()
            return "\t\tException: {0}".format(e)
        # output will be weird, decode to utf-8 to save heartache
        phantom_output = []
        for out_line in output.splitlines():
            phantom_output.append( out_line.decode('utf-8') )

這是python2.7-在python3中可能更容易,但是將其保存在這里是因為花了很多試驗和錯誤才能使subprocess32與phantomjs一起工作。

另外-我沒有共享thumnails.js文件,但是它是javascript,它可以將命令行輸入解析為phantomjs中所需的任意數量的URL,並使用這些參數構造文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM