简体   繁体   English

如何以跨平台方式从另一个Python脚本运行一个Python脚本?

[英]How to run a Python script from another Python script in the cross-platform way?

Here is the problem... 这是问题所在...

I'm writing very small plugin for Blender, I have 10 python scripts, they parsing different file formats by using command-line, and I have a Main Python script to run all other scripts with proper commands... 我正在为Blender写一个非常小的插件,我有10个python脚本,它们通过使用命令行来解析不同的文件格式,并且我有一个Main Python脚本来使用适当的命令运行所有其他脚本...

for example, "Main.py" include: 例如,“ Main.py”包括:

txt2cfg.py -inFile -outFile... txt2cfg.py -inFile -outFile ...
ma2lxo.py -inFile -outFile... ma2lxo.py -inFile -outFile ...

Blender already include Python, so I can run "Main.py" from Blender, But I need it to work with both PC and MAC, and also doesn't require Python installation, so I can't use: Blender已经包含Python,因此我可以从Blender运行“ Main.py”,但是我需要它同时与PC和MAC一起使用,并且不需要Python安装,因此我不能使用:

  • execfile(' txt2cfg.py -inFile -outFile ') execfile('txt2cfg.py -inFile -outFile')
  • os.system(' ma2lxo.py -inFile -outFile ') os.system('ma2lxo.py -inFile -outFile')
  • or even import subprocess 甚至导入子流程

because they required Python installation in order to run *.py files. 因为他们需要安装Python才能运行* .py文件。

Sorry for language 对不起语言

Thanks 谢谢

If you really need to execute a python script in a new process and you don't know where the interpreter you want is located then use the sys module to help out. 如果您确实需要在新进程中执行python脚本,并且不知道所需的解释器在哪里,请使用sys模块来提供帮助。

import sys
import subprocess

subprocess.Popen((sys.executable, "script.py"))

Though importing the module (dynamically if need be) and then running its main method in another script is probably a better idea. 尽管(如果需要的话)动态导入模块,然后在另一个脚本中运行其main方法可能是一个更好的主意。

for example, "Main.py" include: 例如,“ Main.py”包括:

txt2cfg.py -inFile -outFile... ma2lxo.py -inFile -outFile... txt2cfg.py -inFile -outFile ... ma2lxo.py -inFile -outFile ...

Two things. 两件事情。

  1. Each other script needs a main() function and a "main-import switch". 每个其他脚本都需要main()函数和“ main-import开关”。 See http://docs.python.org/tutorial/modules.html#executing-modules-as-scripts for hints on how this must look. 有关该外观的提示,请参见http://docs.python.org/tutorial/modules.html#executing-modules-as-scripts

  2. Import and execute the other scripts. 导入并执行其他脚本。

     import txt2cfg import ma2lxo txt2cfg.main( inFile, outFile ) ma2lxo.main( inFile, outFile ) 

This is the simplest way to do things. 这是做事的最简单方法。

Two options: 两种选择:

  1. Use py2exe to bundle the interpreter with the scripts. 使用py2exe将解释器与脚本捆绑在一起。
  2. Import the modules and call the functions automatically. 导入模块并自动调用功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM