Python - 使用 json 时出现文件处理错误
Python - File Handling error while using json
所以我还在研究python,在下面的脚本中我想完成以下任务:
- 从另一个 VM(即 VM1)接收并保存文件
- 将该文件中的 json 字符串转换为字典
- 检索值,然后执行已在 VM2
中的 bash 文件(即 test.sh
)
代码如下:
在"receiver.py"
import socket
import json
import subprocess
s = socket.socket()
host = '10.0.2.15'
port = 60000
s.connect((host, port))
with open('command.py', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
if not data:
break
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
fh = open("command.py","r")
fh.read()
loaded_r = json.loads(jsonstring)
if loaded_r['task'] == 'allow':
subprocess.call('./test.sh')
else:
print("not found")
在"command.py"
import json
a = {'task': 'allow'}
jsonstring = json.dumps(a)
当我 运行 它时,文件被接收并保存在 VM2 上,但是 bash 文件没有 运行 并且我收到以下错误:
NameError: name 'jsonstring' is not defined
我以为jsonstring
已经在command.py
中定义了,所以我不知道在哪里定义它。感谢您的帮助,提前致谢。
您不必使用 open 来读取 'command.py' 文件。在你写完JSON之后。你可以导入它
EX:
from command import jsonstring
print jsonstring
jsonstring = json.loads(jsonstring)
您不需要以下步骤。因为它不是 JSON 文件。这是一个 python 文件
fh = open("command.py","r")
fh.read()
loaded_r = json.loads(jsonstring)
所以我还在研究python,在下面的脚本中我想完成以下任务:
- 从另一个 VM(即 VM1)接收并保存文件
- 将该文件中的 json 字符串转换为字典
- 检索值,然后执行已在 VM2 中的 bash 文件(即
test.sh
)
代码如下:
在"receiver.py"
import socket
import json
import subprocess
s = socket.socket()
host = '10.0.2.15'
port = 60000
s.connect((host, port))
with open('command.py', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
if not data:
break
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
fh = open("command.py","r")
fh.read()
loaded_r = json.loads(jsonstring)
if loaded_r['task'] == 'allow':
subprocess.call('./test.sh')
else:
print("not found")
在"command.py"
import json
a = {'task': 'allow'}
jsonstring = json.dumps(a)
当我 运行 它时,文件被接收并保存在 VM2 上,但是 bash 文件没有 运行 并且我收到以下错误:
NameError: name 'jsonstring' is not defined
我以为jsonstring
已经在command.py
中定义了,所以我不知道在哪里定义它。感谢您的帮助,提前致谢。
您不必使用 open 来读取 'command.py' 文件。在你写完JSON之后。你可以导入它
EX:
from command import jsonstring
print jsonstring
jsonstring = json.loads(jsonstring)
您不需要以下步骤。因为它不是 JSON 文件。这是一个 python 文件
fh = open("command.py","r")
fh.read()
loaded_r = json.loads(jsonstring)