defmodule Sandbox do
port = Port.open({:spawn,'python3 -u add_server.py'},[:binary|[packet: 4]])
div = fn(a,b)->
port <- {self,{:command,term_to_binary({a,b})}}
receive do {_,{:data,b}} -> binary_to_term(b) after 100->{:error,:timeout} end
end
IO.puts "send {a,b}={32,10}, python result : #{inspect div.(32,10)}"
IO.puts "send {a,b}={2,0}, python result : #{inspect div.(2,0)}"
IO.puts "send {a,b}={1,1}, python result : #{inspect div.(1,1)}"
end
Thanks. It also looks like term_to_binary and binary_to_term should be :erlang.term_to_binary and :erlang.binary_to_term but please correct me if I’m mistaken. (See below)
defmodule Sandbox do
port = Port.open({:spawn,'python3 -u add_server.py'}, binary: true, packet: 4)
div = fn(a,b)->
send(port, {self(),{:command, :erlang.term_to_binary({a,b})}})
receive do {_,{:data,b}} -> :erlang.binary_to_term(b) after 100->{:error,:timeout} end
end
IO.puts "send {a,b}={32,10}, python result : #{inspect div.(32,10)}"
IO.puts "send {a,b}={2,0}, python result : #{inspect div.(2,0)}"
IO.puts "send {a,b}={1,1}, python result : #{inspect div.(1,1)}"
end
Look that binary is not defined in same way as {packet, N :: 1 | 2 | 4} is. Passing [packet: 4] is of course ok since Keyword is a List of Tuple i.e. [packet: 4] == [{:packet, 4}]. However the specification of binary is different. It’s not in Tuple format which means we can’t make it {:binary, true} or with Elixir’s sugar: [binary: true].
The :binary part may be confusing for you. In many places Atom is used as a flag, so when checking arguments we are looking not if binary option is set to true, but if :binary flag is a member of List.