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

我需要根据用户输入执行以下函数:

如果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')


慕码人2483693
浏览 139回答 3
3回答

红颜莎娜

您可以使用三引号来简化事情。if x==0:    path = "test.py"    string = """\import requests, jsonURL = "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, jsonURL = "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)请参阅文档。大约在页面下方的三分之一处。

繁星点点滴滴

new_file = "print('line1')\n" \           "print('line2')\n" \           "print('line3')"f = open('new_python.py', 'w')print(new_file, file=f)

慕田峪7331174

如果你想保存到文件中,最终它必须是一个字符串。该文件的两个变体看起来非常相似,因此不要将其写入两次: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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python