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'] )
Related
I'm trying to download a zip file off the web and trying to download it by console command using wget -O fileName urlLink, but when trying the code, CMD opens for a second then closes and I canno't find the file anywhere.
I've tried using other ways of getting the file downloaded, but they return ERROR 403. Using wget in CMD downloads the right file, but not in the python code.
def gotoDownload(link):
try:
with requests.Session().get(link) as download:
if isUrlOnline(download):
soup = BeautifulSoup(download.content, 'html.parser')
filtered = soup.find_all('script')
zip_file_url = re.search(r"('http.*?')", filtered[17].text).group().replace("'", "")
os.system("wget -O {0} {1}".format('CreatureFinalZTL.zip', zip_file_url))
Expect the file to download
Instead doesn't download anything.
There are a few things that may help here (it may or may not solve your problem, because it is dependent on the your machine's setup and configuration). First, one thing I would suggest is to be more specific on the paths. You can use absolute paths in the wget line like so:
"wget -O {0} {1}".format('/path/to/output/dir/CreatureFinalZTL.zip', zip_file_url)
This is usually helpful in case the Python environment does not operate in a directory you are expecting. Alternatively, you can force the directory with the following python command:
os.chdir( path )
Then, you can operate with relative paths without worry. A second thing I would suggest is to confirm that the url is what you are expecting. Just print it out like so:
print( zip_file_url )
It might sound silly, but it is important to confirm that your regex is operating correctly.
Use subprocess instead.
import subprocess
...
subprocess.run(["wget", "-O", 'CreatureFinalZTL.zip', zip_file_url])
This avoids any shell involvement with the command you wish to run.
Fixed, had to re-add wget to PATHS on windows.
I have a small piece of python3 code. Which runs a command from the terminal.
import os
os.system('"C:/directory/program.exe" -k "C:/directory/options.txt" & pause')
When I run this code in IDLE, I get the following error:
The filename, directory name, or volume label syntax is incorrect.
Both of the paths are valid. So thats not the problem. In addition, running:
"C:/directory/program.exe" -k "C:/directory/options.txt" & pause
from the terminal works correctly.
You don't need quotes around the system paths, this should work:
import os
os.system("C:/directory/program.exe -k C:/directory/options.txt & pause")
Hopefully that helps.
[Edit] Working with spaces like you're doing it with os.system is to my knowledge impossible, referring to this python bug tracker thread
A solution might be using the subprocess module insead.
import subprocess
subprocess.call(["C:/direc tory/program.exe", "-k", "C:/direc tory/program.exe"])
I'm writing a python (ver 2.7) script to automate the set of commands in this Getting Started example for INOTOOL.
Problem: When I run this entire script, I repeatedly encounter these errors:
Current Directory is not empty
No project is found in this directory
No project is found in this directory
But, when I run a first script only up till the code line marked, and manually type in the next three lines, or when I run these last three lines (starting from the "ino init -t blink" line) after manually accessing the beep folder, then I am able to successfully execute the same code.
Is there a limitation with os.system() that I'm encountering?
My code:
import os,sys
def upload()
os.system("cd /home/pi/Downloads")
os.system("mkdir beep")
os.system("cd beep") #will refer to this code junction in question description
os.system("ino init -t blink")
os.system("ino build")
os.system("ino upload")
sys.exit(0)
Yes, when os.system() commands are run for cd , it does not actually change the current directory for the python process' context. From documentation -
os.system(command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
So even though you are changing directory in os.system() call, the next os.system call still occurs in same directory. Which could be causing your issue.
You shoud try using os.chdir() to change the directory instead of os.system() calls.
The Best would be to use subprocess module as #PadraicCunningham explains in his answer.
You can use the subprocess module and os.mkdir to make the directory, you can pass the current working directory cwd to check_callso you actually execute the command in the directory:
from subprocess import check_call
import os
def upload():
d = "/home/pi/Downloads/beep"
os.mkdir(d)
check_call(["ino", "init", "-t", "blink"],cwd=d)
check_call(["ino", "build"],cwd=d)
check_call(["ino", "upload"],cwd=d)
A non-zero exit status will raise CalledProcessError which you may want to catch but once successful you know the commands all returned a 0 exit status.
I wish to write a python script that allows me to navigate and git pull multiple repositories. Basically the script should type the following on the command-line:
cd
cd ~/Desktop/Git_Repo
git pull Git_Repo
I am not sure if there is a python library already out there that can perform such a task.
Use subprocess, os, and shlex. This should work, although you might require some minor tweaking:
import subprocess
import shlex
import os
# relative dir seems to work for me, no /'s or ~'s in front though
dir = 'Desktop/Git_Repo'
# I did get fetch (but not pull) to work
cmd = shlex.split('git pull Git_Repo')
# you need to give it a path to find git, this lets you do that.
env = os.environ
subprocess.Popen(cmd, cwd=dir, env=env)
Also, you'll need your login preconfigured.
I am trying to execute a program from a directory
import os
os.chdir("/home/user/a/b")
with cd("/home/user/a/b"):
run ("./program")
i get cd is not defined...
any help appreciated cheers
I'm not sure what instructions you're following to get what you showed. There is no built-in function called cd or run in Python.
You can call a program in a specific directory using the subprocess module:
import subprocess
subprocess.call("./program", cwd="/home/user/a/b")
The cwd argument causes the call function to automatically switch to that directory before starting the program named in the first argument.
It looks like you are trying to use functionalities of fabric. Make sure fabric is installed, and cd and run are imported from fabric. Something like,
from fabric.context_managers import cd
from fabric.operations import run
import os
os.chdir("/home/user/a/b")
with cd("/home/user/a/b"):
run ("./program")
Save your file as fabfile.py,and from the same directory run it as:
fab -H localhost
For more information on the fabric, checkout: fabric