I want to use python to send command to julia and then get string output as the return and then send the command again. i.e. x=2
and then x+1
return 3
. This required an interactive session through subprocess. I tried the subprocess.Popen(["julia", "-e"]
, the non interactive session and checked that the Julia interface worked. However, when I tried to use the following code to run the Julia interactive session, it got stuck.
import subprocess
class PersistentJulia:
def __init__(self):
# Start Julia in interactive mode
self.process = subprocess.Popen(
["julia", "-i"], # Interactive mode
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True, # Text mode for easier string handling
bufsize=1, # Line-buffered
)
def run_command(self, command):
# Send the command to Julia and read the output
self.process.stdin.write(command + "n")
self.process.stdin.flush()
# Read the output
output = []
while True:
line = self.process.stdout.readline()
if not line or line.startswith("julia>"):
break
output.append(line)
# Return the collected output as a single string
return ''.join(output).strip()
def close(self):
# Close the Julia process
self.process.stdin.write("exit()n")
self.process.stdin.flush()
self.process.stdin.close()
self.process.stdout.close()
self.process.stderr.close()
self.process.terminate()
self.process.wait()
# Example usage
if __name__ == "__main__":
julia = PersistentJulia()
# Run some Julia commands
output1 = julia.run_command('x = 2')
print("Output 1:", output1)
output2 = julia.run_command('x + 3')
print("Output 2:", output2)
output3 = julia.run_command('println("The value of x is ", x)')
print("Output 3:", output3)
# Close the Julia process
julia.close()
The julia = PersistentJulia()
could be ran successfully, but start with
# Run some Julia commands
output1 = julia.run_command('x = 2')
print("Output 1:", output1)
the code got stuck and doesn’t work. It looked fine but I’m not sure which part it went wrong.
I’m not sure if the subprocess was the right way to go, and I don’t want to use the Julia library in python. How to ruan an interactive Julia session in python withouth using the python’s julia library?
2