很抱歉,其他帖子,有一个错误。
我的简化代码:
#test
import json
x = {}
x['x'] = {'y': 1, 'z': 0}
with open('x.json', 'w') as f:
json.dump(x, f)
和
#test2
import json
f = open('x.json')
x = json.load(f)
while x['x']['y'] > 0:
x['x']['z'] = x['x']['z'] + 1
x['x']['y'] = x['x']['y'] - 1
if x['x']['y'] == 0:
print(x['x']['z'])
n = input("Number: ")
while n.isdigit() == False:
print("Not a number")
n = input("Number: ")
if n.isdigit() == True:
x['x']['y'] = int(n)
with open('x.json', 'w') as f:
json.dump(x, f)
我有两个代码,所以我不会用test覆盖test2的数字
这已经是我想要的,但是我对n = 4 和n = 5 的输出是:
1
Number: 4
5
Number: 5
10
Number:
依此类推...
但是,我希望代码完全退出,然后在不手动执行的情况下再次启动它。有点像:
1
Number: 4
代码重新启动
5
Number: 5
代码重新启动
5
Number: 10
,依此类推。谢谢:-)
答案 0 :(得分:0)
如果我对您的理解正确,则必须创建两个单独的脚本
test1.py
#test
import json
import os
x = {}
x['x'] = {'y': 1, 'z': 0}
with open('x.json', 'w') as f:
json.dump(x, f)
os.system('python test2.py') # this line will run the second script
test2.py
import json
f = open('x.json')
x = json.load(f)
while x['x']['y'] > 0:
x['x']['z'] = x['x']['z'] + 1
x['x']['y'] = x['x']['y'] - 1
if x['x']['y'] == 0:
print(x['x']['z'])
n = input("Number: ")
while n.isdigit() == False:
print("Not a number")
n = input("Number: ")
if n.isdigit() == True:
x['x']['y'] = int(n)
with open('x.json', 'w') as f:
json.dump(x, f)