我一直在尝试创建一个打开 axios.post('http://localhost:3000/auth', {
userId: id,
name: name,
email: email
})
.then(function (response) {
this.props.setAuth();
})
.catch(function (error) {
console.log(error);
});
}.bind(this));
文件的python脚本,
输入一个输入,然后读取输出,并根据收到的输出输入另一个输入。
我一直在尝试使用Python的子流程库,但问题是 exe
方法只能使用一次。所以输入2个输入是不可能的,除非你在 communicate()
方法中输入它们,这在这种情况下不起作用。因为第二个输入是基于第一次输入后生成的输出,所以你不能同时输入两个输入。
另外,我搜索了python的第三方库,但是我找不到任何适合windows的好库。
有人可以告诉我使用子流程库执行此操作的方法,还是建议我使用一个好的Windows库?
答案 0 :(得分:0)
考虑一个简单的应用程序,它具有一些基本的执行控制流,只是将其STDIN与STDOUT相反 - 这可以是任何可执行文件,但为了简单起见我们将坚持使用Python - 比如app.py
:
#!/usr/bin/env python
import sys
sys.stdout.write("::BEGIN::\n") # tell our listener that we're listening...
sys.stdout.flush() # flush the STDOUT buffer
while True: # a simple event loop
line = sys.stdin.readline().rstrip() # read a line from STDIN
if line: # ignore empty lines
if line == "::END::": # just a convenient way to shut down the app
sys.stdout.write("::END::\n") # tell our listener that we're done
sys.stdout.flush() # flush the STDOUT buffer
break # we're finished here
sys.stdout.write(line[::-1]) # write the reversed line to STDOUT
sys.stdout.write("\n") # add a new line to the STDOUT
sys.stdout.flush() # flush the STDOUT buffer
然后,如果你想打开这个应用程序并通过Python脚本与它进行通信,你需要做的就是控制子进程STDOUT和STDIN,你可以无限期地执行此操作,例如:
import subprocess
# start our subprocess, forward its STDOUT and STDIN to the internal buffers
proc = subprocess.Popen(["python", "app.py"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
# lets define our data to be sent one by one to our app.py, including ::END:: to exit...
items = ["test", "data", "to", "run", "sequentially", "::END::"]
# a convenience function to get the next item and write it to the passed buffer
def send_next_item(buf):
item = items.pop(0) # pop the first element from `items`
print("REQ: {}".format(item))
buf.write(item) # write it to the passed buffer
buf.write("\n") # write a new line to the passed buffer
buf.flush() # flush the passed buffer
while True: # wait for a prompt by our app
line = proc.stdout.readline().rstrip()
if line == "::BEGIN::":
print("BEGIN!")
send_next_item(proc.stdin) # send the first item to the processes' STDIN
elif line == "::END::":
print("END!")
break # nothing more to do
elif line: # ignore empty lines
print("RES: {}".format(line))
send_next_item(proc.stdin) # send the next item to the processes' STDIN
当你运行它时,你会得到一个输出:
BEGIN! REQ: test RES: tset REQ: data RES: atad REQ: to RES: ot REQ: run RES: nur REQ: sequentially RES: yllaitneuqes REQ: ::END:: END!
当然,您可以进一步处理以决定如何正确响应被调用应用程序的输入请求,这只是一个基本示例。