从集成PythonInterp调用外部脚本

2024-06-16 08:57:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力使用一个简单的Python脚本,我想从另一个用Python编写的程序中调用它。由于我对Python非常陌生,我不知道如何解决这个问题。你知道吗

我使用的是在集成解释器中运行的Artisan。Artisan允许我定义触发操作的按钮,例如调用外部脚本。 在我的例子中,这个外部脚本应该通过串口与Arduino通信。我的外部脚本最初是用Python3编写的,但出于测试目的,我还将代码更改为Python2。 它看起来是这样的:

#!/usr/bin/env python3
import sys
import time
import serial

PORT = '/dev/tty.usbmodemFA131'

with serial.Serial(PORT, 9600) as arduino:
    time.sleep(2)
    arduino.write(sys.argv[1].encode('ASCII'))
    print(arduino.readline())

当我从终端运行这个代码时(我使用的是MacOS10.11.5),它的工作方式和预期的一样。你知道吗

当我从Artisan内部调用它时,Python崩溃,显示以下通知:

Last login: Wed Jul 13 07:21:46 on ttys000 Philipps-Air:~ philipp$ /Applications/Artisan.app/Contents/MacOS/Artisan ; exit; Jul 13 07:22:20 Artisan[40170] : /Applications/Artisan.app/Contents/Resources/lib/python2.7/site-packages.zip/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. Jul 13 07:22:57 Artisan[40170] : Fatal Python error: Py_Initialize: unable to load the file system codec Jul 13 07:22:57 Artisan[40170] : ImportError: No module named 'encodings' Jul 13 07:22:57 Artisan[40170] : Jul 13 07:22:57 Artisan[40170] : Current thread 0x00007fff73660000 (most recent call first):

接下来,我尝试从Artisan内部调用另一个短脚本来调用上述脚本:

from subprocess import call
call(['./arduino.py', sys.argv[1]])

导致相同的错误:/

将代码更改为Python2时,通知会更改,但脚本也不会执行:

^{2}$

我尝试了hash-rpython但是这没有改变任何事情。你知道吗

为了让我的脚本由外部Python(首选Python3)解释器而不是使用Artisan集成的解释器来解释,我必须做些什么?你知道吗

所有的脚本都是可执行的,必要的lib都安装在MacOS附带的Python3和Python2中。你知道吗

非常感谢你的帮助!你知道吗

菲利普


Tags: 代码import脚本timeportsysserialcall