Execute Shell Script from python and assign output to a variable [duplicate] - python

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

Related

How can I use a Python file to execute terminal command? [duplicate]

This question already has answers here:
How can I make one python file run another? [duplicate]
(8 answers)
Closed 2 years ago.
So, all I want is opening a Python script with a Python script? I want the equivalent of 'Python script.py'. Can someone explain how can I execute a. py file. How can I use subprocess to do that? Thanks in advance
With the subprocess module:
import subprocess
subprocess.run(['python', 'script.py'])
If you want to use the same python as the caller you can do:
import subprocess
import sys
subprocess.run([sys.executable, 'script.py'])
There are several ways:
subprocess.call(command)
subprocess.check_call(command)
subprocess.check_output(command)
subprocess.run(command)
os.system(command)
(Each of them has it's own features and you can search in SO to find their differences.
I usually use os.system(command))
Also I found THIS: os.exec*** are realy helpful in these situations

How to write os.system() info to text file? [duplicate]

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.

How to use STDIN from subprocess.Popen [duplicate]

This question already has answers here:
How do I pass a string into subprocess.Popen (using the stdin argument)?
(12 answers)
Closed 6 years ago.
How can I implement something like
$ echo "hello" | my_app
with usage of Python's subprocess?
subprocess.Popen() expects a pipe or a file handle for STDIN. But I want to provide STDIN for the called program via a variable. So something like
myinput = "hello"
subprocess.Popen("an_external_programm", stdin=myinput)
….
I was able to solve my problem by using Popen.communicate()
So some kind of pseudo code:
proc = subprocess.Popen(…)
proc.communicate(input="my_input_via_stdin")
In a python script named myscript.py
import sys
for line in sys.stdin:
print(line)
in unix
echo 'hello' | myscript.py

python run binary application in memory and return output [duplicate]

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

Detect if python script is run from console or by crontab [duplicate]

This question already has answers here:
Checking for interactive shell in a Python script
(5 answers)
Closed 5 years ago.
Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.
Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?
Thank you for your time.
Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:
import sys, os
if os.isatty(sys.stdin.fileno()):
# Debug mode.
pass
else:
# Cron mode.
pass
You could add an environment variable to the crontab line and check, inside your python application, if the environment variable is set.
crontab's configuration file:
CRONTAB=true
# run five minutes after midnight, every day
5 0 * * * /path/to/your/pythonscript
Python code:
import os
if os.getenv('CRONTAB') == 'true':
# do your crontab things
else:
# do your debug things
Use a command line option that only cron will use.
Or a symlink to give the script a different name when called by cron. You can then use sys.argv[0]to distinguish between the two ways to call the script.

Categories