python - 无论如何要重新格式化python脚本?
问题描述
下面我有一个 python 脚本,如果我创建一个.py
文件并将以下代码粘贴到其中,它将无法工作
import os\r\nimport time \r\nimport random \r\n \r\ndef fun_9991():\r\n ## a simple code example to test \r\n for i in range (0 , 10 ):\r\n print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))\r\n print ("loop reached the end")\r\n \r\n \r\nif __name__ == "__main__":\r\n fun_9991()\r\n\r\n\r\n
我的目标是将上面的脚本转换为下面的原始形式,而不必自己编辑
我尝试使用replace()
删除\r\n
但我没有成功
import os
import time
import random
def fun_9991():
## a simple code example to test
for i in range (0 , 10 ):
print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))
print ("loop reached the end")
if __name__ == "__main__":
fun_9991()
解决方案
如果您只是将字符串写入文件,它应该有点工作:
with open('example.py', 'w') as text_file:
text_file.write("""import os\r\nimport time \r\nimport random \r\n \r\ndef fun_9991(): \r\n # a simple code example to test \r\n for i in range (0 , 10 ):\r\n print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))\r\n print ("loop reached the end")\r\n \r\n \r\nif __name__ == "__main__":\r\n fun_9991()\r\n\r\n\r\n""")
如果需要,您也可以只执行代码:
exec("""import os\r\nimport time \r\nimport random \r\n \r\ndef fun_9991(): \r\n # a simple code example to test \r\n for i in range (0 , 10 ):\r\n print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))\r\n print ("loop reached the end")\r\n \r\n \r\nif __name__ == "__main__":\r\n fun_9991()\r\n\r\n\r\n""")
推荐阅读
- amazon-ecs - 如何确定每个日期的 ECS 服务的 Cloudwatch 日志流
- resources - 指示 Colab 是在本地执行代码还是在其他地方的机器上执行代码的标志
- windows - 用户模式访问 Windows 上的 TPM
- java - 使用 Lambda 表达式计算阶乘
- java - 对调用返回实体页面的方法的方法进行单元测试
- flutter - 带有 ClipPath 的全圆角
- python - Pysnmp:nextCmd() 为扩展脚本产生许多结果
- python - 有效地模糊搜索大量数据?
- c++ - 如何在 C++ 中设置字符集,我是初学者
- linux - 将g ++编译器的输出重定向到文件?