为了账号安全,请及时绑定邮箱和手机立即绑定

如何从另一个脚本编写一个脚本?

如何从另一个脚本编写一个脚本?

慕码人2483693 2023-07-27 16:26:13
我需要根据用户输入执行以下函数:如果X=0,则应URL ....Print('Success将行中的内容写入文件并另存为test.py.在后端,Test.py任务调度程序会自动从保存的位置获取保存的文件 ( ) 并定期运行。是的,我们有很多例子来编写一个文件/从另一个文件运行 python,但无法从另一个文件编写 python 脚本。我肯定缺少一些基本步骤。if x=0:   ### Need to write below content to a file & save as test.py######   URL = "https://.../login"   headers  = {"Content-Type":"application/json"}   params = {   "userName":"xx",   "password":"yy"   }   resp = requests.post(URL, headers = headers, data=json.dumps(params))   if resp.status_code != 200:       print('fail')   else:       print('Success')]else:   ### Need to write below content to a file ######   URL = "https://.../login"   headers  = {"Content-Type":"application/json"}   params = {   "userName":"RR",   "password":"TT"   }   resp = requests.post(URL, headers = headers, data=json.dumps(params))   if resp.status_code != 200:       print('fail')   else:       print('Success')
查看完整描述

3 回答

?
红颜莎娜

TA贡献1842条经验 获得超12个赞

您可以使用三引号来简化事情。


if x==0:

    path = "test.py"

    string = """\

import requests, json

URL = "https://.../login"

headers  = {"Content-Type":"application/json"}

params = {

    "userName":"xx",

    "password":"yy"

    }

resp = requests.post(URL, headers = headers, data=json.dumps(params))

if resp.status_code != 200:

    print('fail')

else:

    print('Success')

"""

else:

    path = "other.py"

    string = """\

import requests, json

URL = "https://.../login"

headers  = {"Content-Type":"application/json"}

params = {

    "userName":"RR",

    "password":"TT"

    }

resp = requests.post(URL, headers = headers, data=json.dumps(params))

if resp.status_code != 200:

    print('fail')

else:

    print('Success')

"""


with open(path, 'w') as f:

    f.write(string)



请参阅文档。大约在页面下方的三分之一处。



查看完整回答
反对 回复 2023-07-27
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

new_file = "print('line1')\n" \

           "print('line2')\n" \

           "print('line3')"


f = open('new_python.py', 'w')

print(new_file, file=f)


查看完整回答
反对 回复 2023-07-27
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

如果你想保存到文件中,最终它必须是一个字符串。

该文件的两个变体看起来非常相似,因此不要将其写入两次:


template ='''

URL = "https://.../login"

headers  = {"Content-Type":"application/json"}

params = {

   "userName":"%s",

   "password":"%s"

}

resp = requests.post(URL, headers = headers, data=json.dumps(params))

if resp.status_code != 200:

   print('fail')

else:

   print('Success')

'''


if x == 0:

    content = template % ("xx", "yy")

else:

    content = tempalte % ("RR", "TT")


with open("test.py", "w") as f:

   f.write(content)


查看完整回答
反对 回复 2023-07-27
  • 3 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信