os.sytem('exit') is not working as intended in my code - python

I am trying to install node.js and then check appium version using appium -v
import os,subprocess
os.system('node.msi')
os.system('exit')
os.system('appium -v')
node.msi is a node file on my computer. when i do it through cmd, appium -v works if i do it in a new cmd, but it doesn't work if i keep using the same cmd. so i was hoping that after exit, my code should have worked. can someone point out what i am doing wrong here.

Most likely, the installation of node.msi modifies your system's PATH variable. This change does not become visible inside your running Python process.
If you know the path to your node installation, you can specify it explicitly in a call such as
subprocess.run([r'C:\node\bin\apium.exe', '-v'])

I assume that you are running Windows here. When a console starts, it reads its environment from the registry. That explains why it works when you open a second cmd console.
That means that you have to ask Python to lauch the command appium - v in a new console (and not only a new cmd.exe shell).
It can be done through os.system by using start:
os.system("start /W appium -v")
or depending on what is really appium:
os.system("start /W cmd /c appium -v")
You could also directly use the subprocess module (which offer more configuration than os.system)
p = subprocess.Popen("cmd / c appium -v", creationflags=subprocess.CREATE_NEW_CONSOLE)
p.wait()
Depending on what appium is, the following could be enough:
p = subprocess.Popen("appium -v", creationflags=subprocess.CREATE_NEW_CONSOLE)
p.wait()

Related

How to use python to write wsl shell command? [duplicate]

I'm on Windows using PowerShell and WSL 'Ubuntu 20.04 LTS'. I have no native Linux Distro, and I cant use virtualisation because of nested device reasons.
My purpose is to use a Windows Python script in PowerShell to call WSL to decrypt some avd-snapshots into raw-images. I already tried os.popen, subprocess.Popen/run/call, win32com.client, multiprocessing, etc.
I can boot the WSL shell, but no further commands are getting passed to it. Does somebody know how to get the shell into focus and prepared for more instructions?
Code Example:
from multiprocessing import Process
import win32com.client
import time, os, subprocess
def wsl_shell():
shell = win32com.client.Dispatch("wscript.shell")
shell.SendKeys("Start-Process -FilePath C:\\Programme\\WindowsApps\\CanonicalGroupLimited.Ubuntu20.04onWindows_2004.2021.825.0_x64__79rhkp1fndgsc\\ubuntu2004.exe {ENTER}")
time.sleep(5)
os.popen("ls -l")
if __name__ == '__main__':
ps = Process(target = wsl_shell)
ps.start()
There are a few ways of running WSL scripts/commands from Windows Python, but a SendKeys-based approach is usually the last resort, IMHO, since it's:
Often non-deterministic
Lacks any control logic
Also, avoid the ubuntu2004.exe (or, for other users who find this, the deprecated bash.exe command). The much more capable wsl.exe command is what you are looking for. It has a lot of options for running commands that the <distroname>.exe versions lack.
With that in mind, here are a few simplified examples:
Using os.system
import os
os.system('wsl ~ -e sh -c "ls -l > filelist.txt"')
After running this code in Windows Python, go into your Ubuntu WSL instance and you should find filelist.txt in your home directory.
This works because:
os.system can be used to launch the wsl command
The ~ tells WSL to start in the user's home directory (more deterministic, while being able to avoid specifying each path in this case)
wsl -e sh runs the POSIX shell in WSL (you could also use bash for this)
Passing -c "<command(s)>" to the shell runs those commands in the WSL shell
Given that, you can pretty much run any Linux command(s) from Windows Python. For multiple commands:
Either separate them with a semicolon. E.g.:
os.system('wsl ~ -e sh -c "ls -l > filelist.txt; gzip filelist.txt')
Or better, just put them all in a script in WSL (with a shebang line), set it executable, and run the script via:
wsl -e /path/to/script.sh
That could even by a Linux Python script (assuming the correct shebang line in the script):
wsl -e /path/to/script.py
So if needed, you can even call Linux Python from Windows Python this way.
Using subprocess.run
The os.system syntax is great for "fire and forget" scripts where you don't need to process the results in Python, but often you'll want to capture the output of the WSL/Linux commands for processing in Python.
For that, use subprocess.run:
import subprocess
cp = subprocess.run(["wsl", "~", "-e", "ls", "-l"], capture_output=True)
print(cp.stdout)
As before, the -e argument can be any type of Linux script you want.
Note that subprocess.run also gives you the exit status of the command.

How to launch python from within python Windows 10)?

I am running python3 in Windows 10. Within my program, I try to launch another python instance.
os.system("python -m http.server")
print("All Done")
or
os.system("python")
I want to see a Window shell that pops up and allow me the see the output and interact with it. But instead the program just continues. I don't even see a window pops up. What am I missing?
If you want to open a new window, you need to use start cmd
If you want to open a new window running a command from cmd, that's start cmd /c "command"
e.g
import os
os.system('start cmd /c "python -m http.server"')
However, if you really just want to run another python process, you can import and run the server directly from code - refer docs

Run python script on Windows 10

I am trying to run a simple Python script which runs the ipconfig /all command as a proof of concept.
You can find it below:
from subprocess import PIPE, run
my_command = "ipconfig /all"
result = run(my_command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.stdout, result.stderr)
But I didn't suceed to run it, I tryed both with the command line and by clicking on it but it open a cmd window for 1 second, and then close it so I cannot even read it.
Edit: I am using Python 3.7 and my script is called ipconfig.py
Apparently, your problem is not related to the script itself, but rather to Python interpreter invocation. Check [Python 3.Docs]: How do I run a Python program under Windows?. A general approach would be to:
Open a cmd (PS) window in your script directory
Launch Python (using its full path: check [Python 3.Docs]: Using Python on Windows for more details) on your module (e.g.):
"C:\Program Files\Python37-64\python.exe" ipconfig.py
Of course, there are many ways to improve things, like adding its installation directory in %PATH% (if not already there) in order to avoid specifying its full path every time 1, but take one step at a time.
On the script side: check [Python 3.Docs]: subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None) (and the examples):
Pass the arguments as a list:
my_command = ["ipconfig", "/all"]
You might also want to check the command termination status (result.returncode)
1: If you didn't check Add Python 3.7 to PATH when installing it (check image from 2nd URL), you have to add Python's path (C:\Users\USER\AppData\Local\Programs\Python\Python37) manually. There are many resources on the web, here are 3:
[SuperUser]: How do I add Python to the Windows PATH?
[Geek University]: Add Python to the Windows Path
[RaspberryPi.Projects]: Is Python in your PATH?
Your code is working good.
The problem is that the cmd closes the window too fast and you can't see the result.
Just add a command to wait for your interaction before closing the window.
You can add this at the end of your code:
input("Press Enter to finish...")
Or pause the execution after completion:
import time
[at the end of the code pause for 5 seconds....]
time.sleep(5)

I have python script which included some bash commands in os.system(). Will this work in Windows?

I have a python script which included some bash commands in os.system() method .
If I convert this python script to exe using Pyinstaller, will this exe file work properly in windows OS or will I face any issues since Windows can't run bash commands ?
the bash commands include pdftk utility.
Example : pdftk input_pdf output output_pdf userpw password
Should I install pdftk utility also in Windows.
What should I do or install to make it work in Windows ?
Please help me..
Thank you
It won't work, os.system is os specific, in Windows it will just spawn a cmd process and try to execute that command and cmd != bash.
Edit: powershell has a lot of common bash commands implemented on windows, you could try to figure out in the code what os are you running on and if powershell supports your bash commands you could use the subprocess module to spawn powershell processes
It probably will not work, from what I have seen when using bash commands inside of code on windows.
Solutions:
Change the commands to commands that work on Windows.
Use some kind of python api (if you know of one post it in the comments and I will put it here.) that allows you to use the commands you need.
Simply run the script using the bash terminal on windows, but you won't be able to make it a exe as far as I know.

Can i control PSFTP from a Python script?

i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine.
I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i close PSFTP.
The code which i am trying to run is as follows:
import os
os.system("<directory> -l <username> -pw <password>" )
os.system("cd <anotherDirectory>")
i was just wondering if this is actually possible. Or if there is a better way to do this in Python.
Thanks.
You'll need to run PSFTP as a subprocess and speak directly with the process. os.system spawns a separate subshell each time it's invoked so it doesn't work like typing commands sequentially into a command prompt window. Take a look at the documentation for the standard Python subprocess module. You should be able to accomplish your goal from there. Alternatively, there are a few Python SSH packages available such as paramiko and Twisted. If you're already happy with PSFTP, I'd definitely stick with trying to make it work first though.
Subprocess module hint:
# The following line spawns the psftp process and binds its standard input
# to p.stdin and its standard output to p.stdout
p = subprocess.Popen('psftp -l testuser -pw testpass'.split(),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send the 'cd some_directory' command to the process as if a user were
# typing it at the command line
p.stdin.write('cd some_directory\n')
This has sort of been answered in: SFTP in Python? (platform independent)
http://www.lag.net/paramiko/
The advantage to the pure python approach is that you don't always need psftp installed.

Categories

Resources