As Mojo matures, will there be advantages or disadvantages using it for standard python code? #759
Replies: 1 comment 1 reply
-
I was curious about this myself, so I played around with creating a standalone executable. While it should be possible now, it will require a bit of manual packaging up of things to make it "standalone". The system will need to be able to find the libpython.so shared lib which you can do by specifying a I was able to create an executable that invokes pure python (no 3rd party modules), though I wouldn't call it standalone, since not everything is statically linked in like say a default golang or rust built executable. Even with pure python, the system running the mojo compiled executable will need to have the Create a file # learning.mojo
from python import Python
fn run(cmd: ListLiteral[StringLiteral, StringLiteral]) raises -> None:
let sp = Python.import_module("subprocess")
# Mojo can't do keyword args yet, and it can't do unpacking either (**kwargs). But it
# appears to be able to pass in positional args to python, even if the python method has a
# `*` for kw-only args in the parameter definition
let result = sp.run(
cmd,
# In python, everything after this should be kw-only args, but it looks like mojo can side step this
None, # stdin
None, # input
sp.PIPE, # stdout,
sp.PIPE, # stderr
True, # capture_output
)
print(result.stdout.decode("utf8"))
fn run(cmd: ListLiteral[StringLiteral, StringLiteral, StringLiteral]) raises -> None:
let sp = Python.import_module("subprocess")
let result = sp.run(
cmd,
None,
None,
sp.PIPE,
sp.PIPE,
True
)
print(result.stdout.decode("utf8"))
# You _could_ do this instead of overloading the ListLiteral, but the problem is that calling this:
# run([1, 2, 3])
# would pass the type checker, since T: AnyType. I haven't found anything in the mojo docs for specifying type
# constraints/bounds on the parameter type. This doesn't work either `run[*T: StringLiteral](cmd: ListLiteral[T])`
fn run[*T: AnyType](cmd: ListLiteral[T]) raises -> None:
let sp = Python.import_module("subprocess")
let result = sp.run(
cmd,
None,
None,
sp.PIPE,
sp.PIPE,
True
)
print(result.stdout.decode("utf8"))
fn main():
try:
run(["ls", "-al"])
except ex:
print("Failed to run") Then you build the executable
Which will generate an executable called Note that I said a pure python app. If you use a 3rd party module like say |
Beta Was this translation helpful? Give feedback.
-
Will Mojo create a standalone executable from existing Python code and libraries? I’m interested in taking existing code and adding Mojo enhancements, so is there a reason to migrate to Mojo before modifying existing code to learn the tools on stable code, or wait until Mojo code is added?
Thanks, this is a very exciting project.
Beta Was this translation helpful? Give feedback.
All reactions