Command line from Python 3 - python

I have 1 python 3 script. I need to use another script via command line. What function should i use?
I mean something like that:
res = execute('C:\python32\python Z:\home\192.168.0.15\www\start.pyw start=1 module=server > Z:\home\192.168.0.15\www\test.html')

Use the subprocess module. That gives you the most flexibility.

Check out the Process Management section of the os module
http://docs.python.org/3/library/os.html#module-os
os.popen will work well if you are interested in i/o with the process

This is a python program you want to start. It would be better to import the module, run the method you want and write the output to a file.
However, this would be how you can do it via shell execution:
from subprocess import *
command_stdout = Popen(['C:\python32\python', 'Z:\home\192.168.0.15\www\start.pyw', 'start=1', 'module=server'], stdout=PIPE).communicate()[0]
res = command_stdout.decode("utf-8")
fd = open('Z:\home\192.168.0.15\www\test.html',"w")
fd.write(res)

Related

DOS command in MATLAB

I want to ask about a command in Python that performs exactly like the dos() command in MATLAB. For instance, I have the following code block in MATLAB and I want to do exactly the same in Python.
**DIANA = '"C:\Program Files\Diana 10.3\\bin\\DianaIE.exe"';
MODEL = 'Input.dcp';
INPUTDIR = 'C:\Users\pc\Desktop\Thesis\PSO\';
OUTPUTDIR = 'C:\Users\pc\Desktop\Thesis\PSO\';
OUTPUT = 'FILE_OUTPUT.out';
WORKDIRINPUT = sprintf('%s%s',INPUTDIR,MODEL);
WORKDIROUTPUT = sprintf('%s%s',OUTPUTDIR,OUTPUT);
%
NAMES = sprintf('%s %s %s',DIANA,WORKDIRINPUT,WORKDIROUTPUT);
disp('Start DIANA');
dos(NAMES);
disp('End DIANA');**
To execute a block of code and get the output in python inside the code you can use a function called exec() and pass the expression or the code to be executed as a string.
This accepts the code as a string. Example..
code = 'x=100\nprint(x)'
exec(code)
Output:
100
And if you want to use the command prompt or power shell commands in python you should you a library named os in python
import os
os.system('cd document')
you can use os.path module for manipulation path and a lot more to know more about this go through this documentation OS-Documentation
import subprocess
subprocess.call(['C:\Program Files\Diana 10.3\bin\DianaIE.exe',
'C:\Users\pc\Desktop\Thesis\PSO\Input.py'])

How to use flags/launch arguments when launching programs in python?

I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
livestreamer.exe twitch.tv/streamer best
And here is my python code so far:
import os
streamer=input("Streamer (full name): ")
quality=input("""Quality:
Best
High
Medium
Low
Mobile
: """).lower()
os.chdir("C:\Program Files (x86)\Livestreamer")
os.startfile("livestreamer.exe twitch.tv "+streamer+" "+quality)
I understand that the code is looking for a file not named livestreamer.exe (FileNotFoundError), but one with all the other code put in. Does anyone know how to launch the program with the arguments built in? Thanks.
Use os.system() instead of os.file(). There is no file named "livestreamer.exe twitch.tv "+streamer+" "+quality
Also , os.system() is discouraged , use subprocess.Popen() instead.
Subprocess.Popen() syntax looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.
If it helps, think of subprocess.Popen() as a very flexible os.system().
An example :
sts = os.system("mycmd" + " myarg")
does the same with :
sts = Popen("mycmd" + " myarg", shell=True).wait()
OR
sts = Popen("mycmd" + " myarg", shell=True)
sts.wait()
Source : Subprocess.Popen and os.system()
How about subprocess.call? Something like:
import subprocess
subprocess.call(["livestreamer.exe", "streamer", "best"])

Calling a python script that returns a value from perl

I have a python function as
import commands
output=commands.getputput("ls -l")
print output
return output
I need to get this return value from python function from my perl script
my($command)=`$python_script_path`;
print $command;
My problem is that by printing the ouput in python i can get my results on screen but i actually require this output in Perl script as well so I would rather return it. How can I achieve it ?
Also please note I do not want to use inline python. thanks!!
The commands module is deprecated since 2.6. Use subprocess instead.
p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, shell=True)
print p.communicate()[0]
Return codes are numerical values.
Your best bet is to print the output and capture the output in Perl.
This might help: How to call a python script from Perl?
You also can open pipe to the Python script right in the file 'open':
open PYTHON, "$python_script_path|";
while(<PYTHON>){
print;
}
close PYTHON;

Python subprocess module use

How do you specify what directory the python module subprocess uses to execute commands? I want to run a C program and process it's output in Python in near realtime.
I want to excute the command (this runs my makefile for my C program:
make run_pci
In:
/home/ecorbett/hello_world_pthread
I also want to process the output from the C program in Python. I'm new to Python so example code would be greatly appreciated!
Thanks,
Edward
Use the cwd argument to Popen, call, check_call or check_output. E.g.
subprocess.check_output(["make", "run_pci"],
cwd="/home/ecorbett/hello_world_pthread")
Edit: ok, now I understand what you mean by "near realtime". Try
p = subprocess.Popen(["make", "run_pci"],
stdout=subprocess.PIPE,
cwd="/home/ecorbett/hello_world_pthread")
for ln in p.stdout:
# do processing
Read the documentation. You can specify it with the cwd argument, otherwise it uses the current directory of the parent (i.e., the script running the subprocess).

Python run command line (time)

I want to run the 'time' unix command from a Python script, to time the execution of a non Python app. I would use the os.system method.
Is there any way to save the output of this in Python? My goal is to run the app several times, save their execution times and then do some statistics on them.
Thank You
You really should be using the subprocess module to run external commands. The Popen() method lets you specify a file object where stdout should go (note, you can use any Python object that behaves like a file, you don't necessarily need to write it to a file).
For instance:
import subprocess
log_file = open('/path/to/file', 'a')
return_code = subprocess.Popen(['/usr/bin/foo', 'arg1', 'arg2'], stdout=log_file).wait()
You can use the timeit module to time code snippets (say, a function that launches external commands using subprocess module as described in the answer above) and save the data to a csv file. You can do statistics on the csv data using a stats module or externally using Excel/ LogParser/ R etc.
Another approach is to use the hotshot profiler that does the profiling and also returns stats that you can either print using print_stats() method or save to a file by iterating over.

Categories

Resources