我在 Google Colab 中運行以下代碼并獲取The server encountered an internal error or misconfiguration and was unable to complete your request. 如果我在不傳入$data如下變數的情況下運行命令,它運行得非常好。只有當我遍歷檔案并傳遞變數時,它似乎失敗了
import pandas as pd
import requests
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熱心網友回復:
該!逃逸告訴你的筆記本電腦(谷歌協同合作,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/qukuanlian/384555.html
