我在 Google Colab 中運行以下代碼并獲取The server encountered an internal error or misconfiguration and was unable to complete your request. 如果我在不傳入$data如下變數的情況下運行命令,它運行得非常好。只有當我遍歷檔案并傳遞變數時,它似乎失敗了
import csv
import json
reader = csv.reader(open('/content/drive/MyDrive/file5.csv'))
for row in reader:
data = {"snps": row[0], "pop": "YRI", "r2_threshold": "0.9", "maf_threshold": "0.01"}
data = json.dumps(data)
data = "'{}'".format(data)
!curl -k -H "Content-Type: application/json" -X POST -d "$data" 'https://ldlink.nci.nih.gov/LDlinkRest/snpclip?token=e3e559472899'
這有效:
!curl -k -H "Content-Type: application/json" -X POST -d '{"snps": "rs3\nrs4", "pop":"YRI", "r2_threshold": "0.1", "maf_threshold": "0.01"}' 'https://ldlink.nci.nih.gov/LDlinkRest/snpclip?token=e3e559472899'
uj5u.com熱心網友回復:
更新:實際上,ipython確實允許您!在回圈中運行轉義;代碼中的實際錯誤純粹是參考不正確(尤其是在data值周圍添加了單引號,但可能還有更多)。
下面的原始(部分不正確)答案。
該!逃逸告訴你的筆記本電腦(谷歌Colab,Jupyter,或者你有什么,基本上任何正在運行ipython的內核或類似)離開Python和運行shell命令。Python 本身不支持這個;最接近的近似值類似于
import subprocess
...
for row in reader:
data = {"snps": row[0], "pop": "YRI", "r2_threshold": "0.9", "maf_threshold": "0.01"}
data = json.dumps(data)
# This was wrong on so many levels
# data = "'{}'".format(data)
subprocess.run(['curl', '-k',
'-H', "Content-Type: application/json",
'-X', 'POST', '-d', data,
'https://ldlink.nci.nih.gov/LDlinkRest/snpclip?token=e3e559472899'],
text=True, check=True)
雖然避免subprocess和運行 Pythonurllib或requests代碼來執行POST會更高效和優雅,并讓您更好地控制發送的內容和處理方式。
在 shell 命令和 Python 之間轉換時如何正確參考字串需要您了解 shell 的參考行為。我只是簡單地指出,我在原始命令中沒有錯誤的地方留下了雙引號,但在其他方面更喜歡單引號,當然,data現在指的是具有該名稱的正確 Python 變數,而不是具有相同名稱的 shell 變數.
重申:(ipython這是您的筆記本的介面)知道如何通過!;運行 Python 代碼和 shell scipt 代碼;但是一旦你要求它運行 Python 代碼,ipython把它交給 Python,你就不再處于ipython.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384989.html
標籤:Python 卷曲 jupyter-笔记本 谷歌合作实验室
上一篇:單例模式-
