While going over the subprocess module documentation, I came across the function run and am not sure of its env argument. Here is the definition from the official documentation:
If env is not None, it must be a mapping that defines the
environment variables for the new process; these are used instead of
the default behavior of inheriting the current process’ environment.
It is passed directly to Popen.
Can someone explain this concept to me in the context of the code that I'm stuck on:
import subprocess as sp
foo= sp.run('bash ./foo_1/run_eval.sh foo_3.csv'.split(), env=os.environ.copy())
Its purpose is to allow you to override elements in the default environment.
In other words,
subprocess.run("something", env=os.environ.copy())
is exactly equivalent to just
subprocess.run("something")
It's when you want to override something in the environment that this might come in useful.
myenv = os.environ.copy()
myenv["PATH"] = "%s:%s" % ("/opt/acme/ajax/bin", os.environ["PATH"]))
myenv["SOMETHING_DEFAULTS"] = "increase_frobotzity;crash_less=True"
subprocess.run("something", env=myenv)
Related
I'm refactoring some of my older PS scripts to a) improve them b) clean up c) modularize.
In the script I'm working now there are 10-15 functions that work on specific directory - let's call it work directory. Currently it's defined globally and loaded from a config file; it never changes after initialization (does that make it a constant?).
I want to wrap some of the functions in a separate module. The question is: should I rewrite them so the variable is passed explicitly as a parameter, or can I leave it as is, with the assumption that every script I use this module (library?) in will have this variable initialized? If the latter, how to make sure the module can "detect" the variable is uninitialized and throw some error?
And, last but not least, currently it's just a variable - should I use some specific construct so that it's obvious it is global, and not to be modified?
should I rewrite them so the variable is passed explicitly as a parameter
As long as there's no legitimate use case for overriding it in a single call, I wouldn't pass it as a parameter.
If your functions are packaged as a module, I'd strongly recommend utilizing module-scoped variables rather than globals.
Assuming you're talking about a script module, this is as simple as:
Set-Variable -Scope Script -Name ModuleTargetDirectory -Value $config.TargetDirectory
from inside the module file or a module function that runs during import (the script: scope is the same as module-scope inside a module), and then in the consuming functions:
function Get-Something
{
# ...
$targetDirectory = $script:ModuleTargetDirectory
# ...
}
Or wrap the entire config storage in a private helper method:
# don't export this function
function Get-MyModuleConfig
{
# assuming we stored a dictionary or custom object with the config options in a module-scoped variable named `config`
return $script:config
}
And then always just call $config = Get-MyModuleConfig in the begin block of functions that need access to the config data
i am using pytest-bdd
Here is my feature file
#recon_test.feature
Feature: This is used to run recon
Scenarios:Run Recon
Test File
'''python
#recon_test.py
Class Recon_Tests():
#scenario('recon_test.feature','Run Recon')
def test_run_recon(self):
#do something
when i run this using command pytest , i get error **fixture 'self' not found.**
Because due to scenario annotation it treats this function as fixture maybe , and expects **'self'** to be another fixture.
I want to use the '#scenario' in my test functions inside the test classes . Is there any way ?
Also , i have found a workaround for this , i have created a fixture
```python
def self():
pass
to avoid this , and the error is gone .
But it gives another error saying that 'Recon_Tests' does not have an attribute config.
as bdd tries to read the fixture's config object for pre test hooks.
Please suggest
This is because pytest has no way of knowing whether it is a self (in terms of class instance) or a fixture.
This is fixed when you inherit your class from unittest.TestCase.
Meaning instead of class Recon_Tests() you specify
class ReconTests(unittest.TestCase).
In Matlab, it is easy to generate "help" for a function, as follows.
function out = foo()
% helpful information about foo
end
When we execute help foo, we get "helpful information about foo".
However, suppose we would like to define help for a variable, probably as a definition. How could we do such a thing? It would be nice if we could do something like
x = 3; % m ... position
help x
and get "m ... position". However, I don't believe such functionality exists.
The only reasonable way I see around this is to define every variable as a struct with keys value and description.
x.value = 3;
x.description = 'm/s ... position';
This requires we define every variable as a struct, which is kind of annoying and, I worry (should I?), unperformant (it's simulation code and these variables are accessed repeatedly).
Is there another solution I'm not considering? Should I be worried about making every variable a struct?
Your code should be self-documenting. Instead of variable name x, use position.
Furthermore, all variables should be local, so you can easily look for its definition (with comment) within the function you are editing.
Variables declared further away (with larger scope within the function) should have longer, more self-explanatory names than variables with a smaller scope (e.g. use within a short loop.
There are only two three cases where variables are declared outside the function’s scope:
Class properties. You can actually document these.
In a script, you have access to variables that already existed before the script started. A good reason not to use scripts or depend on the base namespace in larger projects.
Global variables. You should never use global variables for many reasons. Just don’t.
I'm trying to factor out my increasingly big single CoffeeScript file in my Meteor project, and have followed the official advice on scoping global variables using this. However, even something simple like:
console.log("this=" + this)
#gave =
Transactions: new Meteor.Collection("Transactions")
Causes: new Meteor.Collection("Causes")
Generates terminal errors and the server won't start:
=> Meteor server restarted
this=undefined
/home/g/workspace/gave/.meteor/local/build/server/server.js:321
}).run();
^
TypeError: Cannot set property 'gave' of undefined
at app/gave.coffee.js:6:11
According to the advice linked above,
Global variables can be set in CoffeeScript by using this (or CoffeeScript's # shorthand), because at the top level this refers to the global namespace (window on the client and global on the server).
So, I can't really figure out where I'm going wrong. Can you? :)
See ES5 - 15.3.4.4.
NOTE The thisArg value is passed without modification as the this
value. This is a change from Edition 3, where a undefined or null
thisArg is replaced with the global object and ToObject is applied to
all other values and that result is passed as the this value.
So, with the "use strict", meteor's .call(null) will effectively give you a this == null =).
My question is how to program in Python (2.6) a function that uses a namespace of an object, while the function is defined outside the object/class. In addition, that function should only change the variables in the object's namespace; it should not take over the namespace (because with multiple objects they will all use the same namespace).
My reason for pursuing this, is because I wish to write a very small class, where during construction all necessary functions for future use are already given and subsequent function calls (self.__call__) on the object itself can be directly applied.
I realize that this idea is not very pythonic (as they say), and I have thought of various other solutions (such as putting the functions in another class and connecting them), but I can't help but feel that each of these solutions is a lot more work than I would think makes sense.
One simple way that accomplishes what I want is the following:
class A:
def __init__(self, some_dict, func_a):
self.memory = some_dict
self.__call__ = func_a
def test_func(obj, some_input):
if some_input in obj.memory :
return obj.memory[some_input]
else :
obj.memory[some_input] = 0. # some default value
return 0.
first_object = A({}, test_func)
print first_object(first_object, '3')
This will work fine, but what aches me is that when I make function calls to the object, I will also have to give the object itself (see the last line). I hope to be able make calls as such:
print first_object('3')
So far, my ideas were unsuccesful to avoid this (e.g. copying the function method and link its namespace by self.__call__.memory = self.memory). I wish to find something to change the def __init__ part to 'adopt' a function and link their namespaces.
I have rigorously searched for an answer on the internet, but a definite solution has not yet been found. The following http://www.velocityreviews.com/forums/t738476-inserting-class-namespace-into-method-scope.html seeks the same, but is also not succesfull.
Anyone have a solution to tackle this?