Saturday, 19 February 2022

How to delete the contents of a folder?

from pathlib import Path
from shutil import rmtree

for path in Path("/path/to/folder").glob("**/*"):

    if path.is_file():

        path.unlink()

    elif path.is_dir():

        rmtree(path)


from: https://stackoverflow.com/questions/185936/how-to-delete-the-contents-of-a-folder

Check If a File Exists

 import os

os.path.exists('./final_data_2020.csv')


from: https://careerkarma.com/blog/python-check-if-file-exists/

return text between parenthesis

st[st.find("(")+1:st.rfind(")")]

from: https://stackoverflow.com/questions/4894069/regular-expression-to-return-text-between-parenthesis

Tuesday, 25 January 2022

python re.search not working on multiline string

 You need to use the re.S flag, not re.M.

  • re.M (re.MULTILINE) controls the behavior of ^ and $ (whether they match at the start/end of the entire string or of each line).
  • re.S (re.DOTALL) controls the behavior of the . and is the option you need when you want to allow the dot to match newlines.


from: https://stackoverflow.com/questions/27250171/python-re-search-not-working-on-multiline-string

How to execute a program or call a system command?

  1. os.system passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:

    os.system("some_command < input_file | another_command > output_file")  
    

    However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.

  2. os.popen will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. Example:

    print(os.popen("ls -l").read())
    
  3. subprocess.Popen. This is intended as a replacement for os.popen, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:

    print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
    

    instead of

    print os.popen("echo Hello World").read()
    

    but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation.

  4. subprocess.call. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:

    return_code = subprocess.call("echo Hello World", shell=True)
    
  5. subprocess.run. Python 3.5+ only. Similar to the above but even more flexible and returns a CompletedProcess object when the command finishes executing.

  6. os.fork, os.exec, os.spawn are similar to their C language counterparts, but I don't recommend using them directly.


from: https://stackoverflow.com/questions/89228/how-to-execute-a-program-or-call-a-system-command

Friday, 26 November 2021

typing.Callable

 

Callable type; Callable[[int], str] is a function of (int) -> str.

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType. A plain Callable is equivalent to Callable[..., Any], and in turn to collections.abc.Callable.

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec. Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

Deprecated since version 3.9: collections.abc.Callable now supports []. See PEP 585 and Generic Alias Type.

Changed in version 3.10: Callable now supports ParamSpec and Concatenate. See PEP 612 for more information.

 

from:  https://docs.python.org/3/library/typing.html#typing.Callable

Tuesday, 23 November 2021

Python - object MagicMock can't be used in 'await' expression

 You can get mocks to return objects that can be awaited by using a Future. The following is a pytest test case, but something similar should be possible with unittest.

async def test_that_mock_can_be_awaited():
    mock = MagicMock(return_value=Future())
    mock.return_value.set_result(123)
    result = await mock()
    assert result == 123

In your case, since you're patching Service (which gets passed in as mock), mock.return_value = Future() should do the trick.


from: https://stackoverflow.com/questions/51394411/python-object-magicmock-cant-be-used-in-await-expression