Can't rm -r directory using python subprocess.call - python

Welp, I need to remove some huge temporary directories from python and I can't seem to use rm -r. I'm working thought a big dataset (on s3) I don't have the disc space to leave them around.
The usual way I would call a command from python is
import subprocess
subprocess.call('rm','-r','/home/nathan/emptytest')
That gives me
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 629, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer
What's this all about?

You're calling it the wrong way. The first argument should be a list:
import subprocess
subprocess.call(['rm','-r','/home/nathan/emptytest'])
You might also just want to try and use shutitl.rmtree

According to the documentation,
>> In [3]: subprocess.call?
Type: function
Base Class: <type 'function'>
String Form: <function call at 0x01AE79F0>
Namespace: Interactive
File: c:\python26\lib\subprocess.py
Definition: subprocess.call(*popenargs, **kwargs)
Docstring:
Run command with arguments. Wait for command to complete, then
return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
So try:
subprocess.call(['rm','-r','/home/nathan/emptytest'])

Related

Cannot perform subprocess.run inside a snap

In my snap (coded in python), I try to perform some sudo commands but it didn’t work. Here is an example of a command that didn’t work:
command = "sudo netmgr -i country_code set:" + countryCode
subprocess.run([command])
And when I run the snap in my device it won’t work and I got this error:
> Traceback (most recent call last): File
> “/snap/iotr-configuration/x17/bin/iotr-configuration”, line 11, in
> load_entry_point(‘iotr-configure==0.0.3’, ‘console_scripts’,
> ‘iotr-configuration’)() File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/app.py”,
> line 53, in main configuration_program() File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/app.py”,
> line 37, in configuration_program
> confNIC.set_nic_settings(“fd05:a40b:b47d:7340::4”, “1250”) File
> “/snap/iotr-configuration/x17/lib/python3.5/site-packages/src/configureNic.py”,
> line 16, in set_nic_settings subprocess.run([command]) File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 693, in run with Popen(*popenargs, **kwargs) as process: File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 947, in init restore_signals, start_new_session) File
> “/snap/iotr-configuration/x17/usr/lib/python3.5/subprocess.py”, line
> 1551, in _execute_child raise child_exception_type(errno_num, err_msg)
> FileNotFoundError: [Errno 2] No such file or directory: ‘sudo netmgr
> -i country_code set:1250’
This function exist because when I type it directly in the terminal, it works…
Can you help me on this issue ?
You're calling subprocess.run in the wrong way. You should either pass it a the command as a single string (like you're doing here) but then set shell=True, or break the command into several arguments, as in:
command = ["sudo", "netmgr", "-i", "country_code", "set:" + countryside]
subprocess.run(command)
See the FAQ part of the documentation:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

pass selenium webdriver as argoument for python program

i want to run a python program first.py by another program and pass the webdriver
element as an argoument using subprocess doing so:
driver = webdriver.Firefox(executable_path="geckodriver.exe")
process = subprocess.Popen(["python.exe", 'first.py', driver], shell=False)
but python refuses to pass a webdriver element as an argoument
and gives this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\bo\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/bo/Desktop/instagrambot/run_bot.py", line 23, in <lambda>
run_button = tk.Button(root , text="Run", command=lambda: Run())
File "C:/Users/bo/Desktop/instagrambot/run_bot.py", line 12, in Run
close_fds=True)
File "C:\Users\bo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:\Users\bo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1119, in _execute_child
args = list2cmdline(args)
File "C:\Users\bo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 530, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: argument of type 'WebDriver' is not iterable
I'm working on windows 10 and python 3.7
The arguments to the subprocess.Popen call are supposed to be strings whereas you are passing a Python object. This is why you are getting an iteration error - Python attempts to parse the string arguments (that are separated either with a space or a tab) and fails when he gets a Python object.
You have to unfortunately to rethink your strategy. You could construct the driver within the first.py module or have a separate Python module which you could import to get a driver set up when executing the first.py module.

__init__() got an unexpected keyword argument 'timeout' in python subprocess

I am trying to run following code which uses pythos 'subprocess' module.
subprocess.call(cli_args, stdout=client_log, stderr=client_log, timeout=10)
I am using timeout arguement, which is mentioned here to skip from this line if the subprocess stuck at the middle, by killing it.
But when I run this, I am getting following error.
Traceback (most recent call last):
File "test.py", line 152, in <module>
ret = runServiceTest(test_name, server_executable, server_extra_args, client_executable, client_extra_args, protocol, transport, 9090, 0, 0)
File "test.py", line 102, in runServiceTest
ret = subprocess.call(cli_args, stdout=client_log, stderr=client_log, timeout=10)
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
TypeError: __init__() got an unexpected keyword argument 'timeout'
What is the reason for this? How can I solve this? My complete code can be found here.
Judging by your print statements, you are using Python2.x, where subprocess.call does not have a timeout argument:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
https://docs.python.org/2/library/subprocess.html

Running OpenSSL System Call

New to Python and can't get this to work. I need to spawn an openSSL process. Here is what I have:
from subprocess import call
cmd = "openssl aes-128-cbc -d -in ciphertext -base64 -pass pass:test123"
decrypted = call(cmd)
print (decrypted)
This won't even compile. I get TypeError: 'function' object is not subscriptable
Can anyone tell me how I can do this? Thanks.
By the way, when I just type my cmd string into a terminal, it works fine.
EDIT: I changed the line decrypted = call[cmd] to decrypted = call(cmd). When I do that, I get this sequence of errors:
Traceback (most recent call last):
..., line 14, in <module>
plaintext = call(cmd)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/subprocess.py", line 523, in call
with Popen(*popenargs, **kwargs) as p:
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/subprocess.py", line 817, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/subprocess.py", line 1441, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'openssl aes-128-cbc -d -in test.enc -base64 -pass pass:hello'
you use paranthesis instead of square brackets
i.e.:
decrypted = call(cmd)
More generally, you use parenthesis to wrap the arguments in a function call in python (as well as in most other main-stream languages).
Also, by default call treats the first argument as the executable to run, without any argument. You either need to pass shell=True as well, or split the command up into an array and pass that.
decrypted = call(cmd, shell=True) #execute command with the shell
# or
decrypted = call(['openssl', 'aes-128-cbc', '-d', '-in', 'ciphertext', '-base64', '-pass', 'pass:test123'])
In general the latter is preferred because it takes care of escaping for you, and is more portable between different shells.

subprocess.call() for shell program which write a file

I need to execute a shell script using python. Output of shell program is a text file. No inputs to the script. Help me to resolve this.
def invokescript( shfile ):
s=subprocess.Popen(["./Script1.sh"],stderr=subprocess.PIPE,stdin=subprocess.PIPE);
return;
invokescript("Script1.sh");
On using above code., I receive the following error.
Traceback (most recent call last):
File "./test4.py", line 12, in <module>
invokescript("Script1.sh");
File "./test4.py", line 8, in invokescript
s=subprocess.Popen(["./Script1.sh"],stderr=subprocess.PIPE,stdin=subprocess.PIPE);
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error
Thanks in advance...
Try this:
import shlex
def invokescript(shfile):
return subprocess.Popen(
shlex.split(shfile),
stderr=subprocess.PIPE,
stdin=subprocess.PIPE
)
invokescript("Script1.sh");
And add #!/usr/bin/env bash to your bash file of course.
I used os.system() to call shell script. This do what i expected. Make sure that you have imported os module in your python code.
invokescript( "Script1.sh" ) // Calling Function
function invokescript( shfile ): // Function Defenition
os.system("/root/Saranya/Script1.sh")
return;
following is also executable:
invokescript( "Script1.sh" ) // Calling Function
function invokescript( shfile ): // Function Defenition
os.system(shfile)
return;
Thanks for your immediate response guys.

Categories

Resources