【发布时间】:2018-12-05 10:31:09
【问题描述】:
我正在尝试在我的烧瓶网络应用程序中运行 python 脚本。基本上,用户可以单击一个按钮,脚本应该在托管我的烧瓶 python web 应用程序的服务器上运行。我在 Windows Server 2016 和 IIS 上托管它(我知道,我应该考虑 linux)
当用户点击按钮时,服务器会使用如下配置的 os.system 函数执行以下脚本。
def run_python_script(script_path_and_arguments):
try:
command = 'python {}'.format(script_path_and_arguments)
system(command)
return True, 'Success'
except Exception as e:
logger.error('Failed to run script, exception: {}'.format(e))
return False, 'Unknown Error'
当我在我的工作站上本地运行脚本时,它执行正常。 当我从服务器运行脚本时,从命令行,它运行正常, 当我尝试通过网站运行它时,单击按钮失败。
在我看来,它在 IIS 下运行时一定是一些权限/安全问题。你知道我应该在哪里解决它吗?
在服务器上,python.exe 位于 c:\Anaconda3\
编辑:我现在尝试通过使用子进程模块运行脚本来捕获输出:它给出了一个普通异常“命令'python ...'返回非零退出状态1”
def run_python_script(tscript_path_and_arguments):
try:
command = 'python {}'.format(script_path_and_arguments)
output_bytes = subprocess.check_output(command, stderr=subprocess.STDOUT)
output = output_bytes.decode('utf-8')
lines = output.split('\n')
for line in lines:
logger.info(msg='Script output = {}'.format(line))
return True, 'Success'
except Exception as e:
logger.error('Failed to run script, exception: {}'.format(e))
return False, 'Unknown Error'
【问题讨论】:
-
你为什么要在使用python的命令行中调用python?为什么不直接将您需要的模块或脚本导入您的烧瓶应用程序并从那里调用它们呢?这似乎也比让用户在命令行中运行 python 更安全。
-
@Joost 老实说,这是因为脚本是另一个项目的一部分,我当然可以这样做。在实施时,这似乎是正确的做法。
-
经过一些测试和代码剥离(因为普通的 hello world 脚本运行正常),问题出在正在执行的脚本的导入中。我有一些脚本正在导入的模块,但它们在 PYTHONPATH 中。如上所述运行脚本时是否没有考虑 PYTHONPATH?当我剥离这些导入的脚本时,它运行正常。
-
顺便说一句,基于微软方面最近的变化,在不久的将来,必须迁移到 Linux,blog.lextudio.com/… 而不仅仅是“我应该考虑 Linux”。