[英]Executing terminal cmd from Python code returns different result in IDE and terminal itself
我想在Python代碼中執行which jupyter
命令,以便接收我的jupyter
二進制文件的位置。
我的Python腳本ReportGenerator.py
如下所示:
from subprocess import call
if __name__ == "__main__":
call(["which", "jupyter"])
輸出為:
但是,如果我導航到終端中的同一文件夾並執行代碼Python腳本,則:
Kamils-MacBook-Pro-2:項目F1sherKK $ python3 ReportGenerator.py /Users/F1sherKK/.pyenv/versions/3.6.1/bin/jupyter
它可以工作...所以我確保我的PyCharm IDE使用與我的終端相同的python 3.6.1。 我目前不使用任何virtualenv。
有人可以解釋為什么會這樣嗎?
我不知道為什么會這樣,但是這是我從控制台和cron都運行的代碼的用途:
def which(name):
'''
Replace unix 'which' command.
Tested on windows10 and linux mint. Should work on all platforms.
:param name: Requested command name
:type name: str
:return: Full path to command
:rtype: str
'''
for path in os.getenv("PATH").split(os.path.pathsep):
full_path = path + os.sep + name
if os.path.exists(full_path) and os.access(full_path, os.X_OK):
return full_path
raise ValueError('Cant fint command %s')%name
編輯:在Windows上,該函數將在非可執行文件上返回值。 有關為Windows編寫自己的解決方案,請參閱: descusion
subprocess.call()
執行給定的命令並返回該命令的返回碼( 0
=>正常,其他都是錯誤)。
交互式Python Shell(無論是否嵌入在您的IDE中)顯示命令的stdout和stderr流以及返回代碼,但這只是交互式Python Shell的工件-如您所知,它將不會打印任何內容到如果您運行與腳本相同的代碼,則為stdout。
在這里,您想使用subprocess.check_output()
,它將以字符串形式返回命令的輸出。 然后,您需要將該字符串顯式打印到python的進程stdout中:
import subprocess
if __name__ == "__main__":
found = subprocess.check_output(["which", "jupyter"])
print(found)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.