Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...