日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python subprocess popen 无法打开_使用subprocess.Popen()在python脚本中设置PYTHONPATH失败...

發(fā)布時間:2023/12/4 python 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python subprocess popen 无法打开_使用subprocess.Popen()在python脚本中设置PYTHONPATH失败... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本問題已經(jīng)有最佳答案,請猛點這里訪問。

如果自定義模塊不在sys.path變量的任何目錄中,下面的代碼允許我動態(tài)地標識和加載該模塊。

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)這兩個代碼都幫助我設置環(huán)境變量pythonpath,但即使設置了它,我也無法加載該目錄下存在的模塊,也看不到將此目錄項注入sys.path變量中。

subprocess.call(["export PYTHONPATH=/dir"], shell=True)只會影響一個子進程——環(huán)境變量不是全局的,它們不是共享的,它們是從父進程復制到子進程的。設置os.environ["PYTHONPATH"] ="/dir"將不會設置當前進程的sys.path,因為pythonpath是在進程啟動時讀取的,而不是稍后讀取的。

這里發(fā)生了一些事情,可能會讓你有點困惑。一件事是,給popen的任何指令都將在子進程中執(zhí)行,不會影響主進程。您只能通過管道或從中檢索結果。

首先對第二個用例進行注釋,其中使用字符串作為參數(shù)。從文檔中可以看到:

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.

因此,在第二種情況下,您試圖執(zhí)行一個文件或程序x=y,但它不起作用。

即使您像在第一個用例中那樣使用list,您也必須知道,這并不等同于向bash shell傳遞代碼。如果需要,可以使用shell=true作為關鍵字參數(shù),但這還有文檔指出的其他問題。但您的代碼將以shell=true執(zhí)行。

如果您的唯一目的是設置環(huán)境變量,那么您應該考慮使用將環(huán)境變量映射到值的os.environ變量(如@cdarke所示)。

試試這個:

>>> subprocess.call(["export foo=bar && echo foo=$foo"], shell=True)

foo=bar

0

>>>

總結

以上是生活随笔為你收集整理的python subprocess popen 无法打开_使用subprocess.Popen()在python脚本中设置PYTHONPATH失败...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。