Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
_tcontext.pyzdoc
Go to the documentation of this file.
1/**
2\class TDirectory::TContext
3\brief \parblock \endparblock
4\htmlonly
5<div class="pyrootbox">
6\endhtmlonly
7## PyROOT
8
9The functionality offered by TContext can be used in PyROOT with a context manager. Here are a few examples:
10\code{.py}
11import ROOT
12from ROOT import TDirectory
13
14with TDirectory.TContext():
15 # Open some file here
16 file = ROOT.TFile(...)
17 # Retrieve contents from the file
18 histo = file.Get("myhisto")
19
20# After the 'with' statement, the current directory is restored to ROOT.gROOT
21\endcode
22\n
23\code{.py}
24import ROOT
25from ROOT import TDirectory
26
27file1 = ROOT.TFile("file1.root", "recreate")
28#...
29file2 = ROOT.TFile("file2.root", "recreate")
30#...
31file3 = ROOT.TFile("file3.root", "recreate")
32
33# Before the 'with' statement, the current directory is file3 (the last file opened)
34with TDirectory.TContext(file1):
35 # Inside the statement, the current directory is file1
36 histo = ROOT.TH1F(...)
37 histo.Write()
38
39# After the statement, the current directory is restored to file3
40\endcode
41\n
42\code{.py}
43import ROOT
44from ROOT import TDirectory
45
46file1 = ROOT.TFile("file1.root")
47file2 = ROOT.TFile("file2.root")
48
49with TDirectory.TContext(file1, file2):
50 # Manage content in file2
51 histo = ROOT.TH1F(...)
52 # histo will be written to file2
53 histo.Write()
54
55# Current directory is set to 'file1.root'
56\endcode
57
58Note that TContext restores the current directory to its status before the 'with'
59statement, but does not change the status of any file that has been opened inside
60the context (e.g. it does not automatically close the file).
61\htmlonly
62</div>
63\endhtmlonly
64*/