Executing Linux command in Python with special characters - python

I just want to execute the command rm /tmp/*.idx from a python script. I have read that os.system is deprecated (IT IS NOT, see the comments), so I'm trying with Popen the following:
proc = subprocess.Popen(shlex.split('rm /tmp/*.idx'))
proc.communicate()
after of course importing shlex and subprocess, but it doesn't erase the files.
Thanks.

Glob patterns are shell syntax. So:
subprocess.Popen("rm /tmp/*.idx", shell=True)

Related

Untar file with subprocess.call is running successfully but with no effect

Does anyone know what I am doing wrong with this command:
import subprocess
subprocess.call('tar -zvxf %s -C %s' % ("file.tar.gz", '/folder'), shell=True)
The code runs without any errors but the file is only unzipped on random occasions. I know I can use tarfile, but I would like to run it as a Linux command. Any ideas?
If you read the man page, you'll see that the -C parameter is sensitive to order -- it only affects operations that come after it on the command line. So, your file is being unzipped into whatever random directory you happen to be in.
You don't need shell for this. Do:
import os
import subprocess
os.chdir('/folder')
subprocess.call( ['tar','xvfz', 'file.tar.gz'] )

Popen giving error in python when trying to execute a script

Have having issues with Popen in python. Code in question:
from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7 /somescript.py"])
With following error:
failed to run command `/usr/local/bin/python2.7 /somescript.py': No such file or directory
Thing is that when I run the same command in a terminal, it works and the file definitely exists.
You are missing 2 " and a , Popen takes a list of arguments. Try this:
from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7", "/somescript.py"])

Launch python script with abaqus command

I have a command file (.cmd) which I use to launch Abaqus command line windows.
Then, I use the command 'abaqus python test.py' to launch python command inside Abaqus.
Now, I would like to use a python script to do that.
I try something like this but doesn't work. Someone know the trick ?
Thanks !!
import subprocess
AbaqusPath=r"C:\Abaqus\script\abaqus.cmd"
args= AbaqusPath + "-abaqus python test.py"
subprocess.call(args)
Using .cmd-file:
This way might work with cmd file:
abaqusPath = "C:\\Abaqus\\script\\abaqus.cmd /C"
args = AbaqusPath + "abaqus python test.py"
subprocess.call(args)
Flag /C is needed to run command and then terminate.
Easiest way:
Just add the folder with abaqus commands (typical path C:\Abaqus\Commands) into the PATH variable of the system. This will give the access to commands like abaqus, abq6141 etc. in cmd directly.
When just use the following in your script:
subprocess.call("abaqus python test.py")
Using .bat-file:
If the configuration of PATH variable is impossible and the first way does not work, .bat-files from abaqus can be used as follows:
abaqusPath = "C:\\Abaqus\\Commands\\abaqus.bat "
args = AbaqusPath + "python test.py"
subprocess.call(args)
I've never had any success using just string arguments for subprocess functions.
I would try it this way:
import subprocess
abaqus_path = r"C:\Abaqus\script\abaqus.cmd"
subprocess.call([abaqus_path, '-abaqus', 'python', 'test.py'])

Why won't my python subprocess code work? [duplicate]

This question already has answers here:
Using subprocess to run Python script on Windows
(8 answers)
Closed 9 years ago.
from subprocess import *
test = subprocess.Popen('ls')
print test
When i try to run this simple code, I get an error window saying:
WindowsError: [Error 2] The system cannot find the file specified
I have no clue why I can't get this simple code to work and it's frustrating, any help would be greatly appreciated!
It looks like you want to store the output from a subprocess.Popen() call.
For more information see Subprocess - Popen.communicate(input=None).
>>> import subprocess
>>> test = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
fizzbuzz.py
foo.py
[..]
However Windows shell (cmd.exe) doesn't have a ls command, but there's two other alternatives:
Use os.listdir() - This should be the preffered method since it's much easier to work with:
>>> import os
>>> os.listdir("C:\Python27")
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe
', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']
Use Powershell - Installed by default on newer versions of Windows (>= Windows 7):
>>> import subprocess
>>> test = subprocess.Popen(['powershell', '/C', 'ls'], stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
Directory: C:\Python27
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 14.05.2013 16:00 DLLs
d---- 14.05.2013 16:01 Doc
[..]
Shell commands using cmd.exe would be something like this:
test = subprocess.Popen(['cmd', '/C', 'ipconfig'], stdout=subprocess.PIPE)
For more information see:
The ever useful and neat subprocess module - Launch commands in a terminal emulator - Windows
Notes:
Do not use shell=True as it is a security risk.
For more information see Why not just use shell=True in subprocess.Popen in Python?
Do not use from module import *. See why in Language Constructs You Should Not Use
It doesn't even serve a purpose here, when you use subprocess.Popen().
A agree with timss; Windows has no ls command. If you want a directory listing like ls on Windows use dir /B for single-column or dir /w /B for multi-column. Or just use os.listdir. If you do use dir, you must start subprocess using subprocess.Popen(['dir', '/b'], shell=True). If you want to store the output, use subprocess.Popen(['dir', '/b'], shell=True, stdout=subprocess.PIPE). And, the reason I used shell=True is that, since dir is an internal DOS command, the shell must be used to call it. The /b strips the header, and the /w forces multi-column output.

Execute /bin script from other python script

I have a script in my project's bin directory, and I want to execute it from a cron. Both scripts are written in python.
Target file :
App_directory/bin/script_name
Want to execute script_name script with some parameters from App_directory/cron/script_name1.py
How do I achieve that ?
Try:
import os
os.system('/path/to/App_directory/bin/script_name')
Or if script_name is not executable and/or doesn't have the shabang (#!/usr/bin/env python):
import os
os.system('python /path/to/App_directory/bin/script_name')
The subprocess module is much better than using os.system. Just do:
import subprocess
subprocess.call(['/path/to/App_directory/bin/script_name'])
The subprocess.call function returns the returncode (exit status) of the script.
It works for me...
import subprocess
process = subprocess.Popen('script_name')
print process.communicate()

Categories

Resources