python subprocess popen 无法打开_使用subprocess.Popen()在python脚本中设置PYTHONPATH失败...
本問題已經有最佳答案,請猛點這里訪問。
如果自定義模塊不在sys.path變量的任何目錄中,下面的代碼允許我動態地標識和加載該模塊。
import sys
sys.path.append("/lib")
但是,這給了我一個錯誤
import subprocess
x = subprocess.Popen(["export","PYTHONPATH=/lib"], stdout=subprocess.PIPE)
不僅如此,甚至簡單的linux/unix變量聲明設置也會在subprocess.popen()中失敗。
import subprocess
x = subprocess.Popen("x=y", stdout=subprocess.PIPE)
我想檢查子進程,因為我試圖通過os.system()、os.popen()等設置pythonpath,但變量沒有設置(可能是在子進程shell中設置的)。
export是一個內置的shell命令,而不是程序。無論如何,在子進程中設置它不會影響當前的Python進程。你需要os.environdocs.python.org/3/library/os.html嗎?highlight=envir on os.envir‌&8203;打開。
os.environ["pythonpath"]="/dir"和subprocess.call(["export pythonpath=/dir"],shell=true)這兩個代碼都幫助我設置環境變量pythonpath,但即使設置了它,我也無法加載該目錄下存在的模塊,也看不到將此目錄項注入sys.path變量中。
subprocess.call(["export PYTHONPATH=/dir"], shell=True)只會影響一個子進程——環境變量不是全局的,它們不是共享的,它們是從父進程復制到子進程的。設置os.environ["PYTHONPATH"] ="/dir"將不會設置當前進程的sys.path,因為pythonpath是在進程啟動時讀取的,而不是稍后讀取的。
這里發生了一些事情,可能會讓你有點困惑。一件事是,給popen的任何指令都將在子進程中執行,不會影響主進程。您只能通過管道或從中檢索結果。
首先對第二個用例進行注釋,其中使用字符串作為參數。從文檔中可以看到:
class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0, restore_signals=True,
start_new_session=False, pass_fds=())
…
args should be a sequence of program arguments or else a single
string. By default, the program to execute is the first item in args
if args is a sequence. If args is a string, the interpretation is
platform-dependent and described below. See the shell and executable
arguments for additional differences from the default behavior. Unless
otherwise stated, it is recommended to pass args as a sequence.
On POSIX, if args is a string, the string is interpreted as the name
or path of the program to execute. However, this can only be done if
not passing arguments to the program.
因此,在第二種情況下,您試圖執行一個文件或程序x=y,但它不起作用。
即使您像在第一個用例中那樣使用list,您也必須知道,這并不等同于向bash shell傳遞代碼。如果需要,可以使用shell=true作為關鍵字參數,但這還有文檔指出的其他問題。但您的代碼將以shell=true執行。
如果您的唯一目的是設置環境變量,那么您應該考慮使用將環境變量映射到值的os.environ變量(如@cdarke所示)。
試試這個:
>>> subprocess.call(["export foo=bar && echo foo=$foo"], shell=True)
foo=bar
0
>>>
總結
以上是生活随笔為你收集整理的python subprocess popen 无法打开_使用subprocess.Popen()在python脚本中设置PYTHONPATH失败...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中sendkeys.send
- 下一篇: qtabwidget切换tab事件_某超