Python 3 中的网络使用 [英] Net Use in Python 3
问题描述
任何人都可以帮助我尝试使用 NET 使用 python,我不知道 python 和 perl 中的/之间的区别,因为 perl 中的代码有效
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);
但在 Python 3 中不起作用
But in Python 3 don't work
os.system("C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:user pass")
推荐答案
Perl 使用了interpolation,即可以在双引号字符串中嵌入变量,因为 Perl 5 内插变量开始使用 $
或 @
标记.在您的情况下,您正在嵌入 $user_name
和 $passwd
.
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 变量名没有以魔法字符"(sigil)为前缀,因此您不能将它们嵌入字符串中,除非使用格式化语句.有几种机制,这里有一个类似于 printf
的想法:
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)
作为前 Perlmonger,我非常想念插值,我编写了一个 Python 模块来支持它.虽然我在 Python 中学到了很多东西,否则就是在浪费时间.Python 编程是一种不同的风格,您不再需要插值.
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.
顺便说一句,与 Perl 的 system()
不同,Python 的 os.system()
将总是生成一个 shell(就像 C 的一样).因此,它通常被认为已被弃用.subprocess.Popen()
方法提供了更多的控制.
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.
随着 Python 3.6 和 Literal String Interpolation(在 PEP 498 中指定)的出现 - 通常称为 f-strings - 我的原始帖子需要另一种方式来做
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.
可以使用单引号或双引号,甚至是三引号.基本上我们只是把 Python 表达式,通常是一个变量,放在大括号内(类似于 Ruby).
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).
例如:
os.system(f"C:/Windows/System32/net.exe use Z: \\\\ip/D:/ /persistent:no /user:{username} {passwd}")
关于 subprocess.Popen()
的评论也已过时,因为 Python 3.5 首选接口现在是 subprocess.run()
.
The comment about subprocess.Popen()
is also out of date, since Python 3.5 the preferred interface is now subprocess.run()
.
这篇关于Python 3 中的网络使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!