This question already has answers here:
Assign output of os.system to a variable and prevent it from being displayed on the screen [duplicate]
(8 answers)
Closed 5 years ago.
I want to write information about this tracing in file:
site = input('Input URL:')
trac = os.system('tracert '+site)
but trac equals 0 and I don't know how to get access to os.system() information.
Here :
trac = os.system('tracert '+site)
the return value is :
Linux
On Unix, the return value is the exit status of the process encoded in the format specified for wait().
or
Windows
On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC.
For more information about that see python's documentation about os.system.
But if you want to retrieve outputs of your system call then use subprocess.check_output method of subprocess module instead and try to change your code like that :
import subprocess
site = input('Input URL:')
trac = subprocess.check_output(["tracert", site])
# Do something else
Formerly you can did it with os.popen but since Python 2.6 it's deprecated :
Deprecated since version 2.6: All of the popen*() functions are obsolete. Use the subprocess module.
Related
This question already has answers here:
Running shell command and capturing the output
(21 answers)
Closed 2 years ago.
I am executing below shell command in python to get the total number of line in a file and was wondering is there any way to assign the output to a variable in python? Thanks
import os
cmd = "wc -l" + " " + /path/to/file/text.txt
num_rows = os.system(cmd)
Try the os.exec class of functions in the os module. They are designed to execute the OS-dependent versions of the utils you're referring to. Shell scripts can also be executed in these processes.
https://docs.python.org/2/library/os.html#process-management
You may also want to try the subprocess module.
https://docs.python.org/2/library/subprocess.html
This question already has answers here:
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I'm working with python 3.4.1 interpreter in pycharm.
I'm trying to do several things on a changing number of variables.
I'v found it convenient to use exec() in order of changing the variable name and execute the same command on a different variable name.
After doing it successfully for some time, for some reason, errors started to appear.
Those errors happened because I had variables initialization within an exec() command so they weren't recognized by the interpreter.
While changing those lines and removing unnecessary variables, I wrote one command that seems to be running just fine when executes in python console, but won't run in run time or debugging mode.
Usually I use the console as a expression evaluator, so it helps me understand and correct wrong commands, but this time it seems to be the right command and still nothing happens when i'm running the script.
This is the code, doc2text_path was initialized erlier:
$newdir = ""
exec("newdir = " + "doc2text_path%s" % scrape_number)
The command executes and the value of newdir remains "".
newdir is a new variable that i want to create, doc2txt_path is a string variable containing the path of a file I want to write in to later on.
I have about 4 files like that one all referred to with variables in following name format: doc2text_path and a serial number: doc2text_path1 doc2text_path2 etc'
That way i can use a for loop in order of referring to each one of them.
thanks.
This question already has answers here:
Running shell command and capturing the output
(21 answers)
Closed 7 years ago.
I want protect my commercial application with hwid protection, I have this demidecode : http://gnuwin32.sourceforge.net/packages/dmidecode.htm return UUID of computer where run, the problem is need include this in python code ==> run in memory ==> return output and close, is possible this in python ?
or exist another method to get this UUID of computer ?
actual code :
subprocess.Popen('dmidecode.exe -s system-uuid'.split())
Use check_output to get the output of the shell command:
import subprocess
out = subprocess.check_output('dmidecode.exe -s system-uuid').decode('utf-8').strip()
print('system uuid:', out)
# system uuid: 6ba7b810-9dad-11d1-80b4-00c04fd430c8
This question already has answers here:
Actual meaning of 'shell=True' in subprocess
(7 answers)
Closed 7 years ago.
It seems whenever I try to use Python's subprocess module, I find I still don't understand some things. Currently, I was trying to join 3 mp4 files from within a Python module.
When I tried
z ='MP4Box -cat test_0.mp4 -cat test_1.mp4 -cat test_2.mp4 -new test_012d.mp4'
subprocess.Popen(z,shell=True)
Everything worked.
When I tried
z = ['MP4Box', '-cat test_0.mp4', '-cat test_1.mp4', '-cat test_2.mp4', '-new test_012d.mp4']
subprocess.Popen(z,shell=False)
I got the following error:
Option -cat test_0.mp4 unknown. Please check usage
I thought that for shell=False I just needed to supply a list where the first element was the executable I wanted to run and each succeeding element was an argument to that executable. Am I mistaken in this belief, or is there a correct way to create the command I wanted to use?
Also, are there any rules for using Shell=True in subprocess.Popen? So far, all I really know(?) is "don't do it - you can expose your code to Shell injection attacks". Why does Shell=False avoid this problem? Is there ever an actual advantage to using 'Shell=True`?
If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory.
When shell=True is dangerous?
If we execute shell commands that might include unsanitized input from an untrusted source, it will make a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input
Eg. (Taken from docs)
>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / #
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly..
You have to give every single argument as one element of a list:
z = ['MP4Box', '-cat', 'test_0.mp4', '-cat', 'test_1.mp4', '-cat', 'test_2.mp4', '-new', 'test_012d.mp4']
subprocess.Popen(z,shell=False)
This is normally what you want to do, because you don't need to escape especial characters of the shell in filenames.
This question already has answers here:
Is there a portable way to get the current username in Python?
(15 answers)
Closed 6 years ago.
What is the best way to find out the user that a python process is running under?
I could do this:
name = os.popen('whoami').read()
But that has to start a whole new process.
os.environ["USER"]
works sometimes, but sometimes that environment variable isn't set.
import getpass
print(getpass.getuser())
See the documentation of the getpass module.
getpass.getuser()
Return the “login name” of the user. Availability: Unix, Windows.
This function checks the environment variables LOGNAME, USER,
LNAME and USERNAME, in order, and
returns the value of the first one
which is set to a non-empty string. If
none are set, the login name from the
password database is returned on
systems which support the pwd module,
otherwise, an exception is raised.
This should work under Unix.
import os
print(os.getuid()) # numeric uid
import pwd
print(pwd.getpwuid(os.getuid())) # full /etc/passwd info