我需要知道如何从其他目录中存在的python脚本运行python脚本,如以下算法:
if option==true
run /path/to/the/directory/PYTHON SCRIPT
else
ch3ka 指出您可以使用exec
来执行此操作。还有其他方法,如subprocess
或os.system
。
但是Python在设计上与自身配合得很好 - 这是创建和导入模块背后的整个概念。我认为在大多数情况下,您最好将脚本封装在类中,并将以前在脚本的if __name__ == '__main__'
部分中的代码移动到类的__init__
部分中:
class PYTHON_SCRIPT:
def __init__(self):
# put your logic here
然后你可以导入类:
import PYTHON_SCRIPT
# no need to say if a boolean is true, just say if boolean
if option:
PYTHON_SCRIPT()
此外,这还为您提供了能够根据需要使用脚本中的属性的好处。
使用 execfile
。
可执行文件(...) execfile(文件名[, globals[, locals]])
Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
在pyton3中,execfile
消失了。您可以改用exec(open('/path/to/file.py').read())
。
已经在这里回答了如何从 python 执行程序?OS.System 由于路径中的空格而失败
使用子流程模块
import subprocess
subprocess.call(['C:\Temp\a b c\Notepad.exe', 'C:\test.txt'])
其他方法包括在另一篇文章中使用操作系统库或execfile进行系统调用
如果脚本设计得很好,它可能只是启动一个main函数(通常称为main),所以最正确的方法是在你的代码中导入这个main函数并调用它,这是pythonic的方式。您只需要将脚本的目录添加到 python 路径中即可。
如果可能的话,总是尽量避免exec,subprocess,os.system,Popen等。
例:
import sys
sys.path.insert(0, 'path/to/the/directory')
import python_script
sys.path.pop(0)
if option:
python_script.main()