From python script, send cmd to shell to call another script, which starts an interactive interpreter, then send cmds to spawned interpreter

时间:2015-09-01 21:43:13

标签: python python-2.7 web2py interpreter

My main objective:

Using the web2py framework, create a series of web applications to manage a series of images. The images in question are numerous (100,000+ unpublished manuscript pages) and must be split among many applications, so this must be automated.

Where I am stuck:

I must populate the databases of my web2py applications with images using commands that are all generated dynamically.

This is easily achieved through the python interpreter. See: https://gluonframework.wordpress.com/2010/03/02/shell-only-web2py/ (Interactive Mode near the bottom of the page)

I am having trouble sending (piping?) the dynamically generated commands through so they go to where I want them to. (See next section)

Dynamically generated commands:

Send to command line, spawns interactive python interpreter:

python ..\dynamically_generated_app_path\web2py\web2py.py -S Static_Project_Name -M

Send to spawned interactive interpreter (to populate database):

>>> db.image.insert(png_md5=xxxxxxxxxxxxxxxmd5_hashxxxxxxxxx, name=file_name, png_size=9811451, tif_parent_md5=xxxxxxxxxxxxxxxmd5_hashxxxxxxxxx, file_path=open('..\\images\\file_path\\file_name.png', 'rb'), tif_parent_size=30339568)
>>> # more generated insert commands
>>> db.commit()

What I've tried:

Using the subprocess.Popen() constructor:

int_cmd = 'python ..\apps\dynamically_generated_app_path\web2py\web2py.py -S Static_Project_Name -M'
up_cmd = "db.image.insert(png_md5=xxxxxxxxxxxxxxxmd5_hashxxxxxxxxx, name=file_name, png_size=9811451, tif_parent_md5=xxxxxxxxxxxxxxxmd5_hashxxxxxxxxx, file_path=open('..\\images\\file_path\\file_name.png', 'rb'), tif_parent_size=30339568)"

first = subprocess.Popen(int_cmd, stdin=subprocess.PIPE)
first.stdin.write(up_cmd) # Fails to do what I want

What I don't want to do:

Don't want to use PExpect (because I'm on windows and don't feel like using WExpect).

Don't want to use a method that is specific to a single OS. These applications will be distributed to Linux, Mac, and Windows. (Development is occurring on my Windows box)

My background:

I am fairly new to this whole realm and would appreciate an answer that used built-in libraries, cool ways of pushing commands through to spawned shells, and corrections concerning any mistakes of my terminology. The goal is to learn the gory guts of it all, one concept at a time~

Also, critique on how to better phrase questions would also be appreciated.

1 个答案:

答案 0 :(得分:0)

通过subprocess docs,我发现了这一点。

  

警告:使用communicate()而不是.stdin.write.stdout.read.stderr.read,以避免因任何其他操作系统管道缓冲区填满并阻止子进程而导致死锁。

关于这一点,我认为以下更改将修复您的代码。

first.communicate(up_cmd) # Should work

请告诉我这是否适合您,但我认为应该这样做!