从另一个Python文件运行Python过程

时间:2015-01-18 05:05:59

标签: python import bluetooth

我有问题从另一个调用一个python程序。这种解决方案可能无法证明“导入”的合理性。

问题是一个Python脚本与设备有活动的蓝牙连接。我需要第二个Python脚本中的信息通过第一个python脚本的蓝牙端口发送。

基本上,第一个python文件(file1.py)有这个子:

 def output(string):

       bluetoothsock.send(string)

第二个文件应该可以这样做:

file1.output("randomtext")

第一个python文件应该发送“randomtext”字符串。任何想法都会有所帮助!

File1.py示例:

from bluetooth import *
try:
   sock.connect((target_address, port))
   sock.settimeout(timeout)
except:
   print("Timeout",3)


def output(text):
   try:
      sock.send(str(text))
      return ("Sent Successfully!",True)
   except:
      return("Error Sending",False)

1 个答案:

答案 0 :(得分:0)

在file2.py中,执行

import file1
file1.output("randomtext")

解释器将在导入过程中执行try:.. except:file1.py块中的代码,因此套接字将打开&您应该然后能够使用file1.output()发送数据。

如果该deosn无效,请将输出粘贴到您的问题中,包括任何错误消息。

FWIW,file1.py中的代码使用了一些有问题的技术,例如from bluetooth import *try:.. except:没有命名异常。告诉我们蓝牙模块来自哪个包可能是个好主意。