Net Use in Python 3 - python

anyone could help me with python trying to use NET use, I don't know the diferences between / in python and perl, because code in perl works
$runMap = "C:\\Windows\\System32\\net.exe use \\\\$ip\\D\$ /persistent:no /user:$user_name $passwd";
system($runMap);
But in Python 3 don't work
os.system("C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:user pass")

Perl is using interpolation, that is, it is possible to embed variables inside a double quoted string, since Perl 5 interpolated variables start with a $ or a # marker. In your case you are embedding $user_name and $passwd.
Python variable names are not prefixed by a "magic character" (sigil), so you cannot embed them inside strings except by using formatting statements. There are a couple of regimes, here is one which is a similar idea to printf:
cmd = "C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:%s %s" % (username, passwd)
os.system(cmd)
As an ex-Perlmonger I missed interpolation so much I wrote a Python module to support it. While I learnt a lot about Python doing it, it was otherwise a waste of time. Python programming is a different style, you don't need interpolation any more.
By the way, unlike Perl's system(), Python's os.system() will always spawn a shell (as does C's). Therefore it is generally considered to be deprecated. The subprocess.Popen() method gives much more control.
EDIT:
With the advent of Python 3.6 and Literal String Interpolation (specified in PEP 498) - more commonly known as f-strings - my original post needs another way to do it.
Single or double quotes may be used, even triple quotes. Basically we just put the Python expression, commonly a variable, inside braces (similar to Ruby).
So, for example:
os.system(f"C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:{username} {passwd}")
The comment about subprocess.Popen() is also out of date, since Python 3.5 the preferred interface is now subprocess.run().

Related

is f"{expr=}" a new f-string expression (see equal sign before training brace)? from which version of python on?

I have received a python notebook that is full of expressions like f"{expr=}" that in my environment produce error messages:
var=7
print(f"{var=}")
File "<fstring>", line 1
(var=)
^
SyntaxError: invalid syntax
I suspect/expect that it could be in fact a new syntax for f"expr={expr}", i.e. as in the following print statement:
print(f"var={var}")
var=7
In fact I often use expressions like the latter for debug, and it would be nice to have a shorthand for it.
Is that a higher version of python than mine (3.7.6)? Or is it a customization of the fstring module?
Searching for it on the web or in SE was not productive.
And if it is not a standard feature, how can I get it to work?
Answer - Python Version 3.8
f-strings simplified a lot of places where str.format and % style formatting. There was still a place where you want to print a value of the variable or expression and also add some context with the string like variable name or some arbitrary name so that when you have many statements you can differentiate between the printed values. So using variable name followed by value is more common format of print style debugging.
Blockquote
This caused users to write f"name = {name}" and can get unwieldy when
variable names are long like filtered_data_from_third_party would be
written as f"filtered_data_from_third_party =
{filtered_data_from_third_party}". In those cases we resort to shorter
names we understand easily at the context like f"filtered data
{filtered_data_from_third_pary}". f-strings also support format
specifiers so you can write f"{name!r}" which is same as
f"{repr(name)}".
Given the above boilerplate an idea was posted in python-ideas around
a format specifier where you can use it and the f-string would expand
like a macro into <variable_name> = <value_of_variable>. Initially !d
was chosen so f"{name!d}" would expand to f"name={repr(name)}". This
was initially implemented in bpo36774. After discussion !d was changed
to use = with input from Guido and other core devs since there could
be usecases served by !d in the future and to reserve alphabetical
names in format-string for other uses. So this was changed to use = as
the notation for this feature in bpo36817. An overview of it’s usage
is as below with various features available.
Read more here
This feature was discussed in Python issue 36817 and released in Python 3.8.

Escape sequences in vim (neovim) Python feedkeys

I want to be able to control vim/neovim on a per-key basis with python scripting. There is a function called feedkeys in the python vim module (vim.feedkeys) that is nearly what I want. However, I haven't been able to figure out how to send things like function keys, arrow keys, pgup, pgdown etc as it always takes my strings completely literally.
As per the documentation for vim's feedkeys (vimscript version, not python)
feedkeys("\<CR>") simulates pressing of the <Enter> key. But feedkeys('\<CR>') pushes 5 characters.
Things I've tried with the python counterpart that haven't worked (note, <CR> is just an example; I know I can use \n for that. Nonetheless, this should simulate an enter keypress):
vim.feedkeys("\<CR>")
vim.feedkeys("<CR>")
vim.feedkeys("\<CR\>")
vim.call("feedkeys", "\<CR>")
vim.call("feedkeys", '"\<CR>"')
All of these were interpreted literally. I want to do something like
vim.feedkeys("\<F5>") etc. Any ideas?
This isn't ideal, but it solves my issue well enough:
vim.command('call feedkeys("\<F5>")')
In case this is useful to anyone, I've written a general function that will handle the \<> escapes as well as double-quotes:
def fkeys(text):
firstsub = True
for sub in text.split('"'):
if firstsub:
firstsub = False
else:
vim.feedkeys('"')
vim.command(f'call feedkeys("{sub}")')
Sorry for being Captain Obvious, but it doesn't work, because Python is not VimScript.
See :h nvim_replace_termcodes() and :h nvim_feedkeys() for a complete example. In case of <CR>, simply byte value of 13 will do.
You don't, because the interpretation of something like "\<CR>" is a function of VimL string literals. In other words, feedkeys("\<CR>") is the same thing as (probably) feedkeys("\x0d") — the function doesn't see the difference, the interpretation happens at a source code level. Naturally, Python doesn't have the same feature in the same way.
If you don't want to figure out what the escape sequence is for F5 and code it into your Python script, perhaps you could use vim.eval() to eval a VimL expression, e.g. vim.eval(r'feedkeys("\<F5>")').

If the f-string like string formatting available in Julia?

So I am new to Julia and learned various ways of string formatting. Mainly from websites similar to this.
So I use f-strings a lot in Python, not a big fan of .format(). So I was wondering since someone created Formatting.jl Package to bring .format() like feature in Julia, is there any ongoing or useful package which does same for f-strings? Now I googled a bit about it too but didn't find anything.
What my main issue is that I want to replicate this behaviour:
a = 10
b = 20
print(f'The multiplication is = {a * b}')
In case anyone wondering what are f-strings, refer to this.
Yes, it is possible with standard Julia strings:
x = "World!"
y = 42
greeting = "Hello $x, $(y^2) !" # gives "Hello World!, 1764 !"
See also here:
https://docs.julialang.org/en/v1/manual/strings/#string-interpolation
Edit:
The example in the comment above is
j = 10; b = 20
println("The numbers and their square are $j, $b and $(j^2), $(b^2)")
There are multiple packages, of which the least well known but my favourite is PyFormattedStrings.jl.
Compare:
Package
Syntax
PyFormattedStrings.jl
f"Our yield is {harvest(crop):.3G} kg."
Fmt.jl
f"Our yield is {$(harvest(crop)):.3G} kg."
Formatting.jl
fmt("Our yield is {:.3f} kg.", harvest(crop))
(Note that Formatting has no g/G support).
PyFormattedStrings.jl uses the printf syntax, so eg aligning right is done with {var:20g}, and not {var:>20g} as in Python. Fmt.jl does use the Python syntax.
Neither package supports the f"{4+4=}" syntax of Python 3.8. (Though Julia has #show).
If you want more control over numeric formatting than the default string interpolation, you can use the Formatting.jl package in Julia, which provides Python f-string functionality.

In Julia, insert commas into integers for printing like Python 3.6+

I want to insert commas into large integers for printing.
julia> println(123456789) # Some kind of flag/feature inserts commas.
"123,456,789"
In Python 3.6+ this is easy to do:
>>> print(f"{123456789:,d}")
123,456,789
However, it does not appear that the standard Julia print/println functions have this feature at the present time. What can I do using just the print/println functions?
I guess the most straightforward way in some languages would be to use the ' format modifier in printf. I Julia this WOULD look like so:
using Printf # a stdlib that ships with julia which defines #printf
#printf "%'d" 12345678
However, unfortunately, this flag is not yet supported as you can see from the error you'll get:
julia> #printf "%'d" 12345678
ERROR: LoadError: printf format flag ' not yet supported
If you like this feature, maybe you should think about adding it to the Printf stdlib so that everyone would benefit from it. I don't know how difficult this would be though.
UPDATE: Note that although the macro is defined in stdlib Printf, the error above is explicitly thrown in Base/printf.jl:48. I also filed an issue here
Here is a function based on a Regex from "Regular Expressions Cookbook," by Goyvaerts and Levithan, O'Reilly, 2nd Ed, p. 402, that inserts commas into integers returning a string.
function commas(num::Integer)
str = string(num)
return replace(str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => ",")
end
println(commas(123456789))
println(commas(123))
println(commas(123456789123456789123456789123456789))
""" Output
123,456,789
123
123,456,789,123,456,789,123,456,789,123,456,789
"""

Using Popen in Python to execute bat script with variable

I have a python script that is calling a bat script called testrunner.bat which in turns executes a TestSuite in SOAPUI. I actually have gotten the external call to work just fine with the following command:
Popen("testrunner.bat -s\"CCT000 - Deploy Software Release\" -R\"TestSuite Report\" -E\"Default environment\" -Ppath.packages.sq=Y:\\NIGHTLY C:\\CI\\HEDeployment\\CI-XXX-DeploySwRelease")
However, I need to be able to have the software "level" to be dynamic and need to pass the variable level into the command in place of "NIGHTLY" so I can specify if it's nightly software, or stable, etc. I have seen that I should break all the arguments up separately, but I am having a hard time.
subprocess.Popen() can take a list of arguments as well as a string. So, this should work for you:
release_type = "NIGHTLY"
Popen(['testrunner.bat',
'-s"CCT000 - Deploy Software Release"',
'-R"TestSuite Report"',
'-E"Default environment"',
'-Ppath.packages.sq=Y:' + release_type,
'C:CIHEDeploymentCI-XXX-DeploySwRelease'])
As mentioned in the docs, shlex.split can be very useful for splitting your original command string into pieces. However, at least in my case, I had to re-add the double quotes.
Also, recall that single-quoted strings can contain double quotes, and vice versa, so you don't need to escape the quotes here.

Categories