Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

windows - Net Use in Python 3

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...