亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從另一個腳本編寫一個腳本?

如何從另一個腳本編寫一個腳本?

慕碼人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條經驗 獲得超13個贊

您可以使用三引號來簡化事情。


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 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號