Interaction with linux console in python [duplicate] - python

This question already has answers here:
Running shell command and capturing the output
(21 answers)
Closed 2 years ago.
How I can interaction with linux console in python. Open (or not) window with console, and do any command or just typing something and press enter

For example:
import os
os.system('ls')

I like to use both subprocess and os.
These python modules dont necessarily 'open a console and run a command' rather they interface with your shell.
import os
import subprocess
eg
fileCount = int(subprocess.check_output('ls dir/ | wc -l', shell=True).decode().strip())
or
pathToOldest = './someDir/' + oldestFileInDir
os.remove(pathToOldest)
If youre looking to do run a particular command I would go to a search engine and type 'python run shell commmands' or 'run {enter shell command} in pythonX}

Related

Runnig install.sh file with python [duplicate]

This question already has answers here:
How do I execute a program or call a system command?
(65 answers)
Closed 1 year ago.
How can i run install.sh file using python code.Purpose is to implement software update functionality.The sh file is generated using makeself and it is a self-extractable archive.I get this output when i use os.system or subprocess.run
Failed to parse arguments: Unknown option -title
NB: The Script file don't require any arguments
subprocess.call (Python <=3.5) and subprocess.run (Python >3.5) would be a safer alternative to os.system.
Solution 1 : Use SubProcess
import subprocess
subprocess.call(['/path/to/your/script.sh', 'argument1', 'argument2', ..., 'argumentn'])
Solution 2 : Use Os
import os
os.system('/path/to/your/script.sh argument1 argument2 ... argumentn'])
Both will work fine, if you have the choice it's better to use subprocess since it will handle for you the formatting of your command with thing such as space in the command line or special characters.

The "startfile()" function is not working in Python 3.9.7 [duplicate]

This question already has answers here:
Playing mp3 song on python
(17 answers)
Closed 1 year ago.
I wanted to build a script playing an audio file in the background, so i found code on Stack Overflow to run an audio file without the window popping up:
#echo off
set file=song.mp3
( echo Set Sound = CreateObject("WMPlayer.OCX.7"^)
echo Sound.URL = "%file%"
echo Sound.Controls.play
echo do while Sound.currentmedia.duration = 0
echo wscript.sleep 100
echo loop
echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000) >sound.vbs
start /min sound.vbs
When i ran the file in File Explorer, it worked perfectly.
But my main goal is to get a Python script (.py file) to run it for me without having any visuals, so i tried calling the startfile() function from the os module in my python file, like this:
import os
from locate import this_dir
path = str(this_dir())
os.startfile(path + "\\run_song.py")
This time, no errors were provided, but the sound couldn't be heard.
I use Visual Studio Code and Python 3.9.7
Here is the code inside "run_song.py":
from os import startfile
from locate import this_dir
path = str(this_dir())
startfile(path + "\\sound.vbs")
Here Are The Insides Of "sound.vbs":
Set Sound = CreateObject("WMPlayer.OCX.7")
Sound.URL = "song.mp3"
Sound.Controls.play
do while Sound.currentmedia.duration = 0
wscript.sleep 100
loop
wscript.sleep (int(Sound.currentmedia.duration)+1)*1000
Yes, i tried using the VLC module and it didn't work. This error popped up.
FileNotFoundError: Could not find module 'C:\Users\Dani\Desktop\Code\libvlc.dll' (or one of its dependencies). Try using the full path with constructor syntax.
Here Is The Principal File (run_song.py)'s code.
from locate import this_dir
import vlc
path = str(this_dir())
p = vlc.MediaPlayer("file:///" + path + "song.mp3")
p.play()
os.startfile is not the function you are looking for. Take a look at the documentation:
this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.
In order to play music files, you can install vlc python library using
pip3 install python-vlc
And try this simple method:
import vlc
p = vlc.MediaPlayer("C:/path/to/file/file.mp3")
p.play()
(taken from Playing mp3 song on python)

Pass file paths from Python to shell script [duplicate]

This question already has answers here:
Actual meaning of 'shell=True' in subprocess
(7 answers)
Closed 8 months ago.
I would like to run a shell script from Python 3 in Linux passing two arguments that contain file paths to two different files. The shell script then calls a programme written in Python 2.
In Python 3, I call the shell script like this:
import os
import sys
os.chmod('/path/to/sh', 0o777)
subprocess.call(['/path/to/sh', '/path/to/file1', '/path/to/file2'], shell=True)
My shell script looks like this:
#!/bin/sh
set -x
path1=$1
path2=$2
python2 path/to/programme "$path1" "$path2"
Now, the file paths are empty, and the shell script returns something like python2 path/to/programme '' ''. Does someone know how I could correctly pass the file paths so that the programme written in Python 2 can read them?
Or is there even an easier solution such as using subprocess to directly call the programme written in Python 2?
There is no need for the shell script. You can use subprocess to run python2 directly.
a.py
#!/usr/bin/env python3
import subprocess
subprocess.call(['python2', './b.py', 'foo', 'bar'])
b.py
#!/usr/bin/env python2
import sys
print sys.argv
Running ./a.py outputs ['./b.py', 'foo', 'bar'].
You could also try using past.translation instead:
The past module provides an experimental translation package to help with importing and using old Python 2 modules in a Python 3 environment.
shell=True is only needed if you do something like
subprocess.run("/path/to/sh /path/to/file1 /path/to/file2", shell=True)
where the shell will split the single string into arguments that will identify as the program name and its arguments. But you already have the program name and its arguments identified, so
subprocess.run(['/path/to/sh', '/path/to/file1', '/path/to/file2'])
is all you need.
By using a list and shell=True, you are essentially asking Python to execute
sh -c /path/to/sh /path/to/file1 /path/to/file2
which uses /path/to/file1 to set the value of $0, not $1, in the command to execute.

How do I know the location of the Python executable from within the Python script? [duplicate]

This question already has answers here:
Find full path of the Python interpreter?
(3 answers)
Closed 8 years ago.
I am writing a script called deploy.py.
It needs to know the location of the Python executable. Specifically the Python executable that is being used to invoke the script in the first place. The reason is that it will generate a shell script.
This is what I have been doing so far:
import sys
if __name__ == '__main__':
executable = sys.argv[1]
print executable
And call the script as python deploy.py $(which python). This works. Is there a better way to do this?
Of course, I am running from a virtualenv. PYTHONPATH in sys.environ, etc. do not work.
The path to the current Python executable is in sys.executable:
import sys
print(sys.executable)
e.g.
PS C:\> py -c "import sys; print(sys.executable)"
C:\Python34\python.exe

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.

Categories

Resources