我有一个看起来像这样的脚本:
export foo=/tmp/foo
export bar=/tmp/bar
Run Code Online (Sandbox Code Playgroud)
每次我构建时都运行'source init_env'(其中init_env是上面的脚本)来设置一些变量.
为了在Python中实现同样的目的,我运行了这个代码,
reg = re.compile('export (?P<name>\w+)(\=(?P<value>.+))*')
for line in open(file):
m = reg.match(line)
if m:
name = m.group('name')
value = ''
if m.group('value'):
value = m.group('value')
os.putenv(name, value)
Run Code Online (Sandbox Code Playgroud)
但后来有人决定在init_env文件中添加如下行:
export PATH="/foo/bar:/bar/foo:$PATH"
Run Code Online (Sandbox Code Playgroud)
显然我的Python脚本崩溃了.我可以修改Python脚本来处理这一行,但是当有人想出一个在init_env文件中使用的新功能时,它就会破坏.
问题是,是否有一种简单的方法来运行Bash命令并让它修改我的os.environ?
我想在Python脚本中提取7-Zip档案.它工作正常,除了它吐出提取细节(这在我的情况下是巨大的).
有没有办法在提取时避免这些冗长的信息?我没有找到任何"静默"命令行选项7z.exe.
我的命令是
7z.exe -o some_dir x some_archive.7z
Run Code Online (Sandbox Code Playgroud) 继续我之前的问题,我看到要获取我在python中通过Popen生成的进程的错误代码,我必须调用wait()或communic()(可以用来访问Popen stdout和stderr属性):
app7z = '/path/to/7z.exe'
command = [app7z, 'a', dstFile.temp, "-y", "-r", os.path.join(src.Dir, '*')]
process = Popen(command, stdout=PIPE, startupinfo=startupinfo)
out = process.stdout
regCompressMatch = re.compile('Compressing\s+(.+)').match
regErrMatch = re.compile('Error: (.*)').match
errorLine = []
for line in out:
if len(errorLine) or regErrMatch(line):
errorLine.append(line)
if regCompressMatch(line):
# update a progress bar
result = process.wait() # HERE
if result: # in the hopes that 7z returns 0 for correct execution
dstFile.temp.remove()
raise StateError(_("%s: Compression failed:\n%s") % (dstFile.s,
"\n".join(errorLine)))
Run Code Online (Sandbox Code Playgroud)
然而,文档警告wait() …
我的问题几乎与此相同: 显示子进程stdout的小部件? 但是更进一步。
我有以下代码(python2.7):
def btnGoClick(p1):
params = w.line.get()
if len(params) == 0:
return
# create child window
win = tk.Toplevel()
win.title('Bash')
win.resizable(0, 0)
# create a frame to be able to attach the scrollbar
frame = ttk.Frame(win)
# the Text widget - the size of the widget define the size of the window
t = tk.Text(frame, width=80, bg="black", fg="green")
t.pack(side="left", fill="both")
s = ttk.Scrollbar(frame)
s.pack(side="right", fill="y")
# link the text and scrollbar widgets
s.config(command=t.yview)
t.config(yscrollcommand=s.set)
frame.pack()
process = subprocess.Popen(["<bashscript>", …Run Code Online (Sandbox Code Playgroud) 我正在编写一个以特定顺序使用一堆 bash 调用的管道。
如何判断我的命令是否引发错误?
例如,我正在运行一个带有子进程的 Java 程序,当这个进程出错时它不会警告我或退出。
subprocess我的process对象中或对象中是否有具有此实用程序的东西?
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
Run Code Online (Sandbox Code Playgroud)
当我尝试来自Python的建议:“subprocess.Popen”检查成功和错误时,我收到以下错误:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
Run Code Online (Sandbox Code Playgroud)