当我在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"'
子进程args有什么奇怪的东西吗?还是shell环境不对?
接下来,我调整它并将完整的字符串作为一个参数传递,然后我得到了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
的许多不同的变化后,这是与phantomjs
一起使用的:subprocess32
!!!
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,并使用这些参数构造文件名。