【问题标题】:How to use a variable from one python script in another without running the imported script?如何在不运行导入的脚本的情况下在另一个 python 脚本中使用一个变量?
【发布时间】:2018-05-22 05:11:26
【问题描述】:

我有两个脚本正在积极用于编程课程。我的代码注释很好,我的老师更喜欢外部资源,因为有很多不同的解决方案。

但要解决实际问题,我需要创建一个带套接字的服务器(可以使用),然后允许另一台计算机使用单独的脚本(也可以使用)连接到它。问题是在建立连接之后。我希望两者能够来回发送消息。它发送的方式必须是字节形式,我是如何设置的,但返回的字节无法读取。我可以对其进行解码,但我希望它与其他所有内容一起方便地位于命令提示符中。我尝试将主脚本 (Connection.py) 导入辅助脚本 (Client.py),但随后它运行主脚本。有什么办法可以阻止它运行吗?

这是我的主脚本(创建服务器的那个)

#Import socket and base64#
import socket
import base64

#Creating variable for continuous activity#
neverland = True

#Create socket object#
s = socket.socket()
print ("Socket created") #Just for debugging purposes#

#Choose port number for connection#
port = 29759 #Used a random number generator to get this port#

#Bind to the port#
s.bind((' ', port))
print ("Currently using port #%s" %(port)) #Just for debugging purposes#

#Make socket listen for connections#
s.listen(5)
print ("Currently waiting on a connection...") #Just for debugging purposes#

#Loop for establishing a connection and sending a message#
while neverland == True:

    #Establish a connection#
    c, addr = s.accept()
    print ("Got a connection from ", addr) #Just for debugging purposes#

    #Sending custom messages to the client (as a byte)#
    usermessage = input("Enter your message here: ")
    usermessage = base64.b64encode(bytes(usermessage, "utf-8"))
    c.send(usermessage)

    #End the connection#
    c.close()

这是我的辅助脚本(连接到主脚本的那个)

#Import socket module#
import socket
import Connection

#Create a socket object#
s = socket.socket()         

#Define the port on which you want to connect#
port = 29759               

#Connect to the server on local computer#
s.connect(('127.0.0.1', port))

#Receive data from the server#
print (s.recv(1024))
usermessage = base64.b64decode(str(usermessage, "utf-8"))
print (usermessage)

#Close the connection#
s.close()  

在命令提示符下运行它们时,会出现以下错误:

它尝试再次运行主脚本并得到错误,我该如何防止它?

【问题讨论】:

标签: python


【解决方案1】:

通常实现此目的的方法是在读取脚本时不执行任何操作。 IE。你只需定义你的函数、类和变量,如果这个脚本是要直接调用的,你是否应该这样调用它并引用适当的入口点。例如:

myvar = "world"
def main():
    print("Hello", myvar)
if __name__ == "__main__":
    main()

这样您就可以调用您的脚本python example.py 或从另一个脚本导入它并在需要时使用它的内容:import example; print(example.myvar)。

您还可以重构您的脚本,并拥有一个包含通用/共享定义的文件,并且这与上述内容并不相互排斥。

【讨论】:

    猜你喜欢
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多