Python临时目录执行其他进程?

Ant*_*ony 1 python temp

我在Python中有一串Java源代码,我想编译,执行和收集输出(stdout和stderr).不幸的是,据我所知,javac并且java需要真实的文件,所以我必须创建一个临时目录.

做这个的最好方式是什么?tempfile模块似乎面向创建只对Python进程可见的文件和目录.但在这种情况下,我需要Java才能看到它们.但是,我还希望尽可能智能地处理其他内容(例如在完成时删除文件夹或使用适当的系统临时文件夹)

Sha*_*ger 5

tempfile.NamedTemporaryFiletempfile.TemporaryDirectory为您的目的完美地工作.生成的对象有一个.name属性,提供文件系统可见名称java/ javac可以处理得很好,只需确保:

  1. suffix如果编译器坚持使用.java扩展名命名文件,请相应地进行设置
  2. 始终.flush()在将.namea 传递NamedTemporaryFile给外部进程之前调用文件句柄,或者它(通常会)看到一个不完整的文件

如果你不希望Python在关闭对象时清理文件,要么传递delete=FalseNamedTemporaryFile构造函数,要么使用mkstempmkdtemp函数(创建对象,但不要为你清理它们).

例如,您可以这样做:

# Create temporary directory for source and class files
with tempfile.TemporaryDirectory() as d:

    # Write source code
    srcpath = os.path.join(d.name, "myclass.java")
    with open(srcpath, "w") as srcfile:
        srcfile.write('source code goes here')

    # Compile source code
    subprocess.check_call(['javac', srcpath])

    # Run source code
    # Been a while since I've java-ed; you don't include .java or .class
    # when running, right?
    invokename = os.path.splitext(srcpath)[0]
    subprocess.check_call(['java', invokename])
... with block for TemporaryDirectory done, temp directory cleaned up ...
Run Code Online (Sandbox Code Playgroud)